diff --git a/driver/config/provider.go b/driver/config/provider.go index e2d393a3f6b..31fe948cc9b 100644 --- a/driver/config/provider.go +++ b/driver/config/provider.go @@ -93,6 +93,7 @@ const ( KeyOAuth2GrantJWTIssuedDateOptional = "oauth2.grant.jwt.iat_optional" KeyOAuth2GrantJWTMaxDuration = "oauth2.grant.jwt.max_ttl" KeyRefreshTokenHookURL = "oauth2.refresh_token_hook" // #nosec G101 + KeyTokenHookURL = "oauth2.token_hook" // #nosec G101 KeyDevelopmentMode = "dev" ) @@ -420,11 +421,11 @@ func (p *DefaultProvider) AccessTokenStrategy(ctx context.Context, additionalSou return s } -func (p *DefaultProvider) TokenRefreshHookURL(ctx context.Context) *url.URL { - if len(p.getProvider(ctx).String(KeyRefreshTokenHookURL)) == 0 { - return nil - } +func (p *DefaultProvider) TokenHookURL(ctx context.Context) *url.URL { + return p.getProvider(ctx).RequestURIF(KeyTokenHookURL, nil) +} +func (p *DefaultProvider) TokenRefreshHookURL(ctx context.Context) *url.URL { return p.getProvider(ctx).RequestURIF(KeyRefreshTokenHookURL, nil) } diff --git a/driver/registry_base.go b/driver/registry_base.go index 84afce8455e..d2d458427a8 100644 --- a/driver/registry_base.go +++ b/driver/registry_base.go @@ -506,6 +506,7 @@ func (m *RegistryBase) AccessRequestHooks() []oauth2.AccessRequestHook { if m.arhs == nil { m.arhs = []oauth2.AccessRequestHook{ oauth2.RefreshTokenHook(m), + oauth2.TokenHook(m), } } return m.arhs diff --git a/oauth2/.snapshots/TestAuthCodeWithMockStrategy-strategy=jwt-case=0-description=should_pass_request_if_strategy_passes-should_call_refresh_token_hook_if_configured.json b/oauth2/.snapshots/TestAuthCodeWithMockStrategy-strategy=jwt-case=0-description=should_pass_request_if_strategy_passes-should_call_refresh_token_hook_if_configured-hook=legacy.json similarity index 100% rename from oauth2/.snapshots/TestAuthCodeWithMockStrategy-strategy=jwt-case=0-description=should_pass_request_if_strategy_passes-should_call_refresh_token_hook_if_configured.json rename to oauth2/.snapshots/TestAuthCodeWithMockStrategy-strategy=jwt-case=0-description=should_pass_request_if_strategy_passes-should_call_refresh_token_hook_if_configured-hook=legacy.json diff --git a/oauth2/.snapshots/TestAuthCodeWithMockStrategy-strategy=jwt-case=0-description=should_pass_request_if_strategy_passes-should_call_refresh_token_hook_if_configured-hook=new.json b/oauth2/.snapshots/TestAuthCodeWithMockStrategy-strategy=jwt-case=0-description=should_pass_request_if_strategy_passes-should_call_refresh_token_hook_if_configured-hook=new.json new file mode 100644 index 00000000000..28176f90826 --- /dev/null +++ b/oauth2/.snapshots/TestAuthCodeWithMockStrategy-strategy=jwt-case=0-description=should_pass_request_if_strategy_passes-should_call_refresh_token_hook_if_configured-hook=new.json @@ -0,0 +1,48 @@ +{ + "session": { + "id_token": { + "id_token_claims": { + "jti": "", + "iss": "http://localhost:4444/", + "sub": "foo", + "aud": [ + "app-client" + ], + "nonce": "", + "at_hash": "", + "acr": "1", + "amr": null, + "c_hash": "", + "ext": { + "hooked": "legacy" + } + }, + "headers": { + "extra": { + } + }, + "username": "", + "subject": "foo" + }, + "extra": { + "hooked": "legacy" + }, + "client_id": "app-client", + "consent_challenge": "", + "exclude_not_before_claim": false, + "allowed_top_level_claims": [] + }, + "request": { + "client_id": "app-client", + "granted_scopes": [ + "offline", + "openid", + "hydra.*" + ], + "granted_audience": [], + "grant_types": [ + "refresh_token" + ], + "payload": {} + } +} diff --git a/oauth2/.snapshots/TestAuthCodeWithMockStrategy-strategy=jwt-case=2-description=should_pass_because_prompt=none_and_max_age_is_less_than_auth_time-should_call_refresh_token_hook_if_configured.json b/oauth2/.snapshots/TestAuthCodeWithMockStrategy-strategy=jwt-case=2-description=should_pass_because_prompt=none_and_max_age_is_less_than_auth_time-should_call_refresh_token_hook_if_configured-hook=legacy.json similarity index 100% rename from oauth2/.snapshots/TestAuthCodeWithMockStrategy-strategy=jwt-case=2-description=should_pass_because_prompt=none_and_max_age_is_less_than_auth_time-should_call_refresh_token_hook_if_configured.json rename to oauth2/.snapshots/TestAuthCodeWithMockStrategy-strategy=jwt-case=2-description=should_pass_because_prompt=none_and_max_age_is_less_than_auth_time-should_call_refresh_token_hook_if_configured-hook=legacy.json diff --git a/oauth2/.snapshots/TestAuthCodeWithMockStrategy-strategy=jwt-case=2-description=should_pass_because_prompt=none_and_max_age_is_less_than_auth_time-should_call_refresh_token_hook_if_configured-hook=new.json b/oauth2/.snapshots/TestAuthCodeWithMockStrategy-strategy=jwt-case=2-description=should_pass_because_prompt=none_and_max_age_is_less_than_auth_time-should_call_refresh_token_hook_if_configured-hook=new.json new file mode 100644 index 00000000000..28176f90826 --- /dev/null +++ b/oauth2/.snapshots/TestAuthCodeWithMockStrategy-strategy=jwt-case=2-description=should_pass_because_prompt=none_and_max_age_is_less_than_auth_time-should_call_refresh_token_hook_if_configured-hook=new.json @@ -0,0 +1,48 @@ +{ + "session": { + "id_token": { + "id_token_claims": { + "jti": "", + "iss": "http://localhost:4444/", + "sub": "foo", + "aud": [ + "app-client" + ], + "nonce": "", + "at_hash": "", + "acr": "1", + "amr": null, + "c_hash": "", + "ext": { + "hooked": "legacy" + } + }, + "headers": { + "extra": { + } + }, + "username": "", + "subject": "foo" + }, + "extra": { + "hooked": "legacy" + }, + "client_id": "app-client", + "consent_challenge": "", + "exclude_not_before_claim": false, + "allowed_top_level_claims": [] + }, + "request": { + "client_id": "app-client", + "granted_scopes": [ + "offline", + "openid", + "hydra.*" + ], + "granted_audience": [], + "grant_types": [ + "refresh_token" + ], + "payload": {} + } +} diff --git a/oauth2/.snapshots/TestAuthCodeWithMockStrategy-strategy=jwt-case=5-description=should_pass_with_prompt=login_when_authentication_time_is_recent-should_call_refresh_token_hook_if_configured.json b/oauth2/.snapshots/TestAuthCodeWithMockStrategy-strategy=jwt-case=5-description=should_pass_with_prompt=login_when_authentication_time_is_recent-should_call_refresh_token_hook_if_configured-hook=legacy.json similarity index 100% rename from oauth2/.snapshots/TestAuthCodeWithMockStrategy-strategy=jwt-case=5-description=should_pass_with_prompt=login_when_authentication_time_is_recent-should_call_refresh_token_hook_if_configured.json rename to oauth2/.snapshots/TestAuthCodeWithMockStrategy-strategy=jwt-case=5-description=should_pass_with_prompt=login_when_authentication_time_is_recent-should_call_refresh_token_hook_if_configured-hook=legacy.json diff --git a/oauth2/.snapshots/TestAuthCodeWithMockStrategy-strategy=jwt-case=5-description=should_pass_with_prompt=login_when_authentication_time_is_recent-should_call_refresh_token_hook_if_configured-hook=new.json b/oauth2/.snapshots/TestAuthCodeWithMockStrategy-strategy=jwt-case=5-description=should_pass_with_prompt=login_when_authentication_time_is_recent-should_call_refresh_token_hook_if_configured-hook=new.json new file mode 100644 index 00000000000..28176f90826 --- /dev/null +++ b/oauth2/.snapshots/TestAuthCodeWithMockStrategy-strategy=jwt-case=5-description=should_pass_with_prompt=login_when_authentication_time_is_recent-should_call_refresh_token_hook_if_configured-hook=new.json @@ -0,0 +1,48 @@ +{ + "session": { + "id_token": { + "id_token_claims": { + "jti": "", + "iss": "http://localhost:4444/", + "sub": "foo", + "aud": [ + "app-client" + ], + "nonce": "", + "at_hash": "", + "acr": "1", + "amr": null, + "c_hash": "", + "ext": { + "hooked": "legacy" + } + }, + "headers": { + "extra": { + } + }, + "username": "", + "subject": "foo" + }, + "extra": { + "hooked": "legacy" + }, + "client_id": "app-client", + "consent_challenge": "", + "exclude_not_before_claim": false, + "allowed_top_level_claims": [] + }, + "request": { + "client_id": "app-client", + "granted_scopes": [ + "offline", + "openid", + "hydra.*" + ], + "granted_audience": [], + "grant_types": [ + "refresh_token" + ], + "payload": {} + } +} diff --git a/oauth2/.snapshots/TestAuthCodeWithMockStrategy-strategy=opaque-case=0-description=should_pass_request_if_strategy_passes-should_call_refresh_token_hook_if_configured.json b/oauth2/.snapshots/TestAuthCodeWithMockStrategy-strategy=opaque-case=0-description=should_pass_request_if_strategy_passes-should_call_refresh_token_hook_if_configured-hook=legacy.json similarity index 100% rename from oauth2/.snapshots/TestAuthCodeWithMockStrategy-strategy=opaque-case=0-description=should_pass_request_if_strategy_passes-should_call_refresh_token_hook_if_configured.json rename to oauth2/.snapshots/TestAuthCodeWithMockStrategy-strategy=opaque-case=0-description=should_pass_request_if_strategy_passes-should_call_refresh_token_hook_if_configured-hook=legacy.json diff --git a/oauth2/.snapshots/TestAuthCodeWithMockStrategy-strategy=opaque-case=0-description=should_pass_request_if_strategy_passes-should_call_refresh_token_hook_if_configured-hook=new.json b/oauth2/.snapshots/TestAuthCodeWithMockStrategy-strategy=opaque-case=0-description=should_pass_request_if_strategy_passes-should_call_refresh_token_hook_if_configured-hook=new.json new file mode 100644 index 00000000000..28176f90826 --- /dev/null +++ b/oauth2/.snapshots/TestAuthCodeWithMockStrategy-strategy=opaque-case=0-description=should_pass_request_if_strategy_passes-should_call_refresh_token_hook_if_configured-hook=new.json @@ -0,0 +1,48 @@ +{ + "session": { + "id_token": { + "id_token_claims": { + "jti": "", + "iss": "http://localhost:4444/", + "sub": "foo", + "aud": [ + "app-client" + ], + "nonce": "", + "at_hash": "", + "acr": "1", + "amr": null, + "c_hash": "", + "ext": { + "hooked": "legacy" + } + }, + "headers": { + "extra": { + } + }, + "username": "", + "subject": "foo" + }, + "extra": { + "hooked": "legacy" + }, + "client_id": "app-client", + "consent_challenge": "", + "exclude_not_before_claim": false, + "allowed_top_level_claims": [] + }, + "request": { + "client_id": "app-client", + "granted_scopes": [ + "offline", + "openid", + "hydra.*" + ], + "granted_audience": [], + "grant_types": [ + "refresh_token" + ], + "payload": {} + } +} diff --git a/oauth2/.snapshots/TestAuthCodeWithMockStrategy-strategy=opaque-case=2-description=should_pass_because_prompt=none_and_max_age_is_less_than_auth_time-should_call_refresh_token_hook_if_configured.json b/oauth2/.snapshots/TestAuthCodeWithMockStrategy-strategy=opaque-case=2-description=should_pass_because_prompt=none_and_max_age_is_less_than_auth_time-should_call_refresh_token_hook_if_configured-hook=legacy.json similarity index 100% rename from oauth2/.snapshots/TestAuthCodeWithMockStrategy-strategy=opaque-case=2-description=should_pass_because_prompt=none_and_max_age_is_less_than_auth_time-should_call_refresh_token_hook_if_configured.json rename to oauth2/.snapshots/TestAuthCodeWithMockStrategy-strategy=opaque-case=2-description=should_pass_because_prompt=none_and_max_age_is_less_than_auth_time-should_call_refresh_token_hook_if_configured-hook=legacy.json diff --git a/oauth2/.snapshots/TestAuthCodeWithMockStrategy-strategy=opaque-case=2-description=should_pass_because_prompt=none_and_max_age_is_less_than_auth_time-should_call_refresh_token_hook_if_configured-hook=new.json b/oauth2/.snapshots/TestAuthCodeWithMockStrategy-strategy=opaque-case=2-description=should_pass_because_prompt=none_and_max_age_is_less_than_auth_time-should_call_refresh_token_hook_if_configured-hook=new.json new file mode 100644 index 00000000000..28176f90826 --- /dev/null +++ b/oauth2/.snapshots/TestAuthCodeWithMockStrategy-strategy=opaque-case=2-description=should_pass_because_prompt=none_and_max_age_is_less_than_auth_time-should_call_refresh_token_hook_if_configured-hook=new.json @@ -0,0 +1,48 @@ +{ + "session": { + "id_token": { + "id_token_claims": { + "jti": "", + "iss": "http://localhost:4444/", + "sub": "foo", + "aud": [ + "app-client" + ], + "nonce": "", + "at_hash": "", + "acr": "1", + "amr": null, + "c_hash": "", + "ext": { + "hooked": "legacy" + } + }, + "headers": { + "extra": { + } + }, + "username": "", + "subject": "foo" + }, + "extra": { + "hooked": "legacy" + }, + "client_id": "app-client", + "consent_challenge": "", + "exclude_not_before_claim": false, + "allowed_top_level_claims": [] + }, + "request": { + "client_id": "app-client", + "granted_scopes": [ + "offline", + "openid", + "hydra.*" + ], + "granted_audience": [], + "grant_types": [ + "refresh_token" + ], + "payload": {} + } +} diff --git a/oauth2/.snapshots/TestAuthCodeWithMockStrategy-strategy=opaque-case=5-description=should_pass_with_prompt=login_when_authentication_time_is_recent-should_call_refresh_token_hook_if_configured.json b/oauth2/.snapshots/TestAuthCodeWithMockStrategy-strategy=opaque-case=5-description=should_pass_with_prompt=login_when_authentication_time_is_recent-should_call_refresh_token_hook_if_configured-hook=legacy.json similarity index 100% rename from oauth2/.snapshots/TestAuthCodeWithMockStrategy-strategy=opaque-case=5-description=should_pass_with_prompt=login_when_authentication_time_is_recent-should_call_refresh_token_hook_if_configured.json rename to oauth2/.snapshots/TestAuthCodeWithMockStrategy-strategy=opaque-case=5-description=should_pass_with_prompt=login_when_authentication_time_is_recent-should_call_refresh_token_hook_if_configured-hook=legacy.json diff --git a/oauth2/.snapshots/TestAuthCodeWithMockStrategy-strategy=opaque-case=5-description=should_pass_with_prompt=login_when_authentication_time_is_recent-should_call_refresh_token_hook_if_configured-hook=new.json b/oauth2/.snapshots/TestAuthCodeWithMockStrategy-strategy=opaque-case=5-description=should_pass_with_prompt=login_when_authentication_time_is_recent-should_call_refresh_token_hook_if_configured-hook=new.json new file mode 100644 index 00000000000..28176f90826 --- /dev/null +++ b/oauth2/.snapshots/TestAuthCodeWithMockStrategy-strategy=opaque-case=5-description=should_pass_with_prompt=login_when_authentication_time_is_recent-should_call_refresh_token_hook_if_configured-hook=new.json @@ -0,0 +1,48 @@ +{ + "session": { + "id_token": { + "id_token_claims": { + "jti": "", + "iss": "http://localhost:4444/", + "sub": "foo", + "aud": [ + "app-client" + ], + "nonce": "", + "at_hash": "", + "acr": "1", + "amr": null, + "c_hash": "", + "ext": { + "hooked": "legacy" + } + }, + "headers": { + "extra": { + } + }, + "username": "", + "subject": "foo" + }, + "extra": { + "hooked": "legacy" + }, + "client_id": "app-client", + "consent_challenge": "", + "exclude_not_before_claim": false, + "allowed_top_level_claims": [] + }, + "request": { + "client_id": "app-client", + "granted_scopes": [ + "offline", + "openid", + "hydra.*" + ], + "granted_audience": [], + "grant_types": [ + "refresh_token" + ], + "payload": {} + } +} diff --git a/oauth2/oauth2_auth_code_test.go b/oauth2/oauth2_auth_code_test.go index 1a6bbe4275d..b4811fead10 100644 --- a/oauth2/oauth2_auth_code_test.go +++ b/oauth2/oauth2_auth_code_test.go @@ -235,7 +235,7 @@ func TestAuthCodeWithDefaultStrategy(t *testing.T) { assert.True(t, i.Get("active").Bool(), "%s", i) assert.EqualValues(t, conf.ClientID, i.Get("client_id").String(), "%s", i) assert.EqualValues(t, expectedSubject, i.Get("sub").String(), "%s", i) - assert.EqualValues(t, `{"foo":"bar"}`, i.Get("ext").Raw, "%s", i) + assert.EqualValues(t, `bar`, i.Get("ext.foo").String(), "%s", i) return i } @@ -260,7 +260,7 @@ func TestAuthCodeWithDefaultStrategy(t *testing.T) { assert.True(t, time.Now().After(time.Unix(i.Get("nbf").Int(), 0)), "%s", i) assert.True(t, time.Now().Before(time.Unix(i.Get("exp").Int(), 0)), "%s", i) requirex.EqualTime(t, expectedExp, time.Unix(i.Get("exp").Int(), 0), time.Second) - assert.EqualValues(t, `{"foo":"bar"}`, i.Get("ext").Raw, "%s", i) + assert.EqualValues(t, `bar`, i.Get("ext.foo").String(), "%s", i) assert.EqualValues(t, `["hydra","offline","openid"]`, i.Get("scp").Raw, "%s", i) return i } @@ -682,6 +682,197 @@ func TestAuthCodeWithDefaultStrategy(t *testing.T) { assert.Empty(t, uiClaims.Get(f).Raw, "%s: %s", f, uiClaims) } }) + + t.Run("case=add ext claims from hook if configured", func(t *testing.T) { + run := func(strategy string) func(t *testing.T) { + return func(t *testing.T) { + hs := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + assert.Equal(t, r.Header.Get("Content-Type"), "application/json; charset=UTF-8") + + var hookReq hydraoauth2.TokenHookRequest + require.NoError(t, json.NewDecoder(r.Body).Decode(&hookReq)) + require.NotEmpty(t, hookReq.Session) + require.Equal(t, hookReq.Session.Extra, map[string]interface{}{"foo": "bar"}) + require.NotEmpty(t, hookReq.Request) + require.ElementsMatch(t, hookReq.Request.GrantedAudience, []string{}) + require.Equal(t, hookReq.Request.Payload, map[string][]string{}) + + claims := map[string]interface{}{ + "hooked": true, + } + + hookResp := hydraoauth2.TokenHookResponse{ + Session: consent.AcceptOAuth2ConsentRequestSession{ + AccessToken: claims, + IDToken: claims, + }, + } + + w.WriteHeader(http.StatusOK) + require.NoError(t, json.NewEncoder(w).Encode(&hookResp)) + })) + defer hs.Close() + + reg.Config().MustSet(ctx, config.KeyAccessTokenStrategy, strategy) + reg.Config().MustSet(ctx, config.KeyTokenHookURL, hs.URL) + + defer reg.Config().MustSet(ctx, config.KeyTokenHookURL, nil) + + expectAud := "https://api.ory.sh/" + c, conf := newOAuth2Client(t, testhelpers.NewCallbackURL(t, "callback", testhelpers.HTTPServerNotImplementedHandler)) + testhelpers.NewLoginConsentUI(t, reg.Config(), + acceptLoginHandler(t, c, subject, func(r *hydra.OAuth2LoginRequest) *hydra.AcceptOAuth2LoginRequest { + assert.False(t, r.Skip) + assert.EqualValues(t, []string{expectAud}, r.RequestedAccessTokenAudience) + return nil + }), + acceptConsentHandler(t, c, subject, func(r *hydra.OAuth2ConsentRequest) { + assert.False(t, *r.Skip) + assert.EqualValues(t, []string{expectAud}, r.RequestedAccessTokenAudience) + })) + + code, _ := getAuthorizeCode(t, conf, nil, + oauth2.SetAuthURLParam("audience", "https://api.ory.sh/"), + oauth2.SetAuthURLParam("nonce", nonce)) + require.NotEmpty(t, code) + + token, err := conf.Exchange(context.Background(), code) + require.NoError(t, err) + + assertJWTAccessToken(t, strategy, conf, token, subject, time.Now().Add(reg.Config().GetAccessTokenLifespan(ctx))) + + // NOTE: using introspect to cover both jwt and opaque strategies + accessTokenClaims := introspectAccessToken(t, conf, token, subject) + require.True(t, accessTokenClaims.Get("ext.hooked").Bool()) + + idTokenClaims := assertIDToken(t, token, conf, subject, nonce, time.Now().Add(reg.Config().GetIDTokenLifespan(ctx))) + require.True(t, idTokenClaims.Get("hooked").Bool()) + } + } + + t.Run("strategy=opaque", run("opaque")) + t.Run("strategy=jwt", run("jwt")) + }) + + t.Run("case=fail token exchange if hook fails", func(t *testing.T) { + run := func(strategy string) func(t *testing.T) { + return func(t *testing.T) { + hs := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusInternalServerError) + })) + defer hs.Close() + + reg.Config().MustSet(ctx, config.KeyAccessTokenStrategy, strategy) + reg.Config().MustSet(ctx, config.KeyTokenHookURL, hs.URL) + + defer reg.Config().MustSet(ctx, config.KeyTokenHookURL, nil) + + expectAud := "https://api.ory.sh/" + c, conf := newOAuth2Client(t, testhelpers.NewCallbackURL(t, "callback", testhelpers.HTTPServerNotImplementedHandler)) + testhelpers.NewLoginConsentUI(t, reg.Config(), + acceptLoginHandler(t, c, subject, func(r *hydra.OAuth2LoginRequest) *hydra.AcceptOAuth2LoginRequest { + assert.False(t, r.Skip) + assert.EqualValues(t, []string{expectAud}, r.RequestedAccessTokenAudience) + return nil + }), + acceptConsentHandler(t, c, subject, func(r *hydra.OAuth2ConsentRequest) { + assert.False(t, *r.Skip) + assert.EqualValues(t, []string{expectAud}, r.RequestedAccessTokenAudience) + })) + + code, _ := getAuthorizeCode(t, conf, nil, + oauth2.SetAuthURLParam("audience", "https://api.ory.sh/"), + oauth2.SetAuthURLParam("nonce", nonce)) + require.NotEmpty(t, code) + + _, err := conf.Exchange(context.Background(), code) + require.Error(t, err) + } + } + + t.Run("strategy=opaque", run("opaque")) + t.Run("strategy=jwt", run("jwt")) + }) + + t.Run("case=fail token exchange if hook denies the request", func(t *testing.T) { + run := func(strategy string) func(t *testing.T) { + return func(t *testing.T) { + hs := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusForbidden) + })) + defer hs.Close() + + reg.Config().MustSet(ctx, config.KeyAccessTokenStrategy, strategy) + reg.Config().MustSet(ctx, config.KeyTokenHookURL, hs.URL) + + defer reg.Config().MustSet(ctx, config.KeyTokenHookURL, nil) + + expectAud := "https://api.ory.sh/" + c, conf := newOAuth2Client(t, testhelpers.NewCallbackURL(t, "callback", testhelpers.HTTPServerNotImplementedHandler)) + testhelpers.NewLoginConsentUI(t, reg.Config(), + acceptLoginHandler(t, c, subject, func(r *hydra.OAuth2LoginRequest) *hydra.AcceptOAuth2LoginRequest { + assert.False(t, r.Skip) + assert.EqualValues(t, []string{expectAud}, r.RequestedAccessTokenAudience) + return nil + }), + acceptConsentHandler(t, c, subject, func(r *hydra.OAuth2ConsentRequest) { + assert.False(t, *r.Skip) + assert.EqualValues(t, []string{expectAud}, r.RequestedAccessTokenAudience) + })) + + code, _ := getAuthorizeCode(t, conf, nil, + oauth2.SetAuthURLParam("audience", "https://api.ory.sh/"), + oauth2.SetAuthURLParam("nonce", nonce)) + require.NotEmpty(t, code) + + _, err := conf.Exchange(context.Background(), code) + require.Error(t, err) + } + } + + t.Run("strategy=opaque", run("opaque")) + t.Run("strategy=jwt", run("jwt")) + }) + + t.Run("case=fail token exchange if hook response is malformed", func(t *testing.T) { + run := func(strategy string) func(t *testing.T) { + return func(t *testing.T) { + hs := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusOK) + })) + defer hs.Close() + + reg.Config().MustSet(ctx, config.KeyAccessTokenStrategy, strategy) + reg.Config().MustSet(ctx, config.KeyTokenHookURL, hs.URL) + + defer reg.Config().MustSet(ctx, config.KeyTokenHookURL, nil) + + expectAud := "https://api.ory.sh/" + c, conf := newOAuth2Client(t, testhelpers.NewCallbackURL(t, "callback", testhelpers.HTTPServerNotImplementedHandler)) + testhelpers.NewLoginConsentUI(t, reg.Config(), + acceptLoginHandler(t, c, subject, func(r *hydra.OAuth2LoginRequest) *hydra.AcceptOAuth2LoginRequest { + assert.False(t, r.Skip) + assert.EqualValues(t, []string{expectAud}, r.RequestedAccessTokenAudience) + return nil + }), + acceptConsentHandler(t, c, subject, func(r *hydra.OAuth2ConsentRequest) { + assert.False(t, *r.Skip) + assert.EqualValues(t, []string{expectAud}, r.RequestedAccessTokenAudience) + })) + + code, _ := getAuthorizeCode(t, conf, nil, + oauth2.SetAuthURLParam("audience", "https://api.ory.sh/"), + oauth2.SetAuthURLParam("nonce", nonce)) + require.NotEmpty(t, code) + + _, err := conf.Exchange(context.Background(), code) + require.Error(t, err) + } + } + + t.Run("strategy=opaque", run("opaque")) + t.Run("strategy=jwt", run("jwt")) + }) } // TestAuthCodeWithMockStrategy runs the authorization_code flow against various ConsentStrategy scenarios. @@ -1019,157 +1210,227 @@ func TestAuthCodeWithMockStrategy(t *testing.T) { }) t.Run("should call refresh token hook if configured", func(t *testing.T) { - hs := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Header.Get("Content-Type"), "application/json; charset=UTF-8") - - expectedGrantedScopes := []string{"openid", "offline", "hydra.*"} - expectedSubject := "foo" - - var hookReq hydraoauth2.RefreshTokenHookRequest - require.NoError(t, json.NewDecoder(r.Body).Decode(&hookReq)) - require.Equal(t, hookReq.Subject, expectedSubject) - require.ElementsMatch(t, hookReq.GrantedScopes, expectedGrantedScopes) - require.ElementsMatch(t, hookReq.GrantedAudience, []string{}) - require.Equal(t, hookReq.ClientID, oauthConfig.ClientID) - require.NotEmpty(t, hookReq.Session) - require.Equal(t, hookReq.Session.Subject, expectedSubject) - require.Equal(t, hookReq.Session.ClientID, oauthConfig.ClientID) - require.Equal(t, hookReq.Session.Extra, map[string]interface{}{}) - require.NotEmpty(t, hookReq.Requester) - require.Equal(t, hookReq.Requester.ClientID, oauthConfig.ClientID) - require.ElementsMatch(t, hookReq.Requester.GrantedScopes, expectedGrantedScopes) - - except := []string{ - "session.kid", - "session.id_token.expires_at", - "session.id_token.headers.extra.kid", - "session.id_token.id_token_claims.iat", - "session.id_token.id_token_claims.exp", - "session.id_token.id_token_claims.rat", - "session.id_token.id_token_claims.auth_time", - } - snapshotx.SnapshotTExcept(t, hookReq, except) - - claims := map[string]interface{}{ - "hooked": true, - } - - hookResp := hydraoauth2.RefreshTokenHookResponse{ - Session: consent.AcceptOAuth2ConsentRequestSession{ - AccessToken: claims, - IDToken: claims, - }, + run := func(hookType string) func(t *testing.T) { + return func(t *testing.T) { + hs := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + assert.Equal(t, r.Header.Get("Content-Type"), "application/json; charset=UTF-8") + + expectedGrantedScopes := []string{"openid", "offline", "hydra.*"} + expectedSubject := "foo" + + exceptKeys := []string{ + "session.kid", + "session.id_token.expires_at", + "session.id_token.headers.extra.kid", + "session.id_token.id_token_claims.iat", + "session.id_token.id_token_claims.exp", + "session.id_token.id_token_claims.rat", + "session.id_token.id_token_claims.auth_time", + } + + if hookType == "legacy" { + var hookReq hydraoauth2.RefreshTokenHookRequest + require.NoError(t, json.NewDecoder(r.Body).Decode(&hookReq)) + require.Equal(t, hookReq.Subject, expectedSubject) + require.ElementsMatch(t, hookReq.GrantedScopes, expectedGrantedScopes) + require.ElementsMatch(t, hookReq.GrantedAudience, []string{}) + require.Equal(t, hookReq.ClientID, oauthConfig.ClientID) + require.NotEmpty(t, hookReq.Session) + require.Equal(t, hookReq.Session.Subject, expectedSubject) + require.Equal(t, hookReq.Session.ClientID, oauthConfig.ClientID) + require.NotEmpty(t, hookReq.Requester) + require.Equal(t, hookReq.Requester.ClientID, oauthConfig.ClientID) + require.ElementsMatch(t, hookReq.Requester.GrantedScopes, expectedGrantedScopes) + + snapshotx.SnapshotTExcept(t, hookReq, exceptKeys) + } else { + var hookReq hydraoauth2.TokenHookRequest + require.NoError(t, json.NewDecoder(r.Body).Decode(&hookReq)) + require.NotEmpty(t, hookReq.Session) + require.Equal(t, hookReq.Session.Subject, expectedSubject) + require.Equal(t, hookReq.Session.ClientID, oauthConfig.ClientID) + require.NotEmpty(t, hookReq.Request) + require.Equal(t, hookReq.Request.ClientID, oauthConfig.ClientID) + require.ElementsMatch(t, hookReq.Request.GrantedScopes, expectedGrantedScopes) + require.ElementsMatch(t, hookReq.Request.GrantedAudience, []string{}) + require.Equal(t, hookReq.Request.Payload, map[string][]string{}) + + snapshotx.SnapshotTExcept(t, hookReq, exceptKeys) + } + + claims := map[string]interface{}{ + "hooked": hookType, + } + + hookResp := hydraoauth2.TokenHookResponse{ + Session: consent.AcceptOAuth2ConsentRequestSession{ + AccessToken: claims, + IDToken: claims, + }, + } + + w.WriteHeader(http.StatusOK) + require.NoError(t, json.NewEncoder(w).Encode(&hookResp)) + })) + defer hs.Close() + + if hookType == "legacy" { + conf.MustSet(ctx, config.KeyRefreshTokenHookURL, hs.URL) + defer conf.MustSet(ctx, config.KeyRefreshTokenHookURL, nil) + } else { + conf.MustSet(ctx, config.KeyTokenHookURL, hs.URL) + defer conf.MustSet(ctx, config.KeyTokenHookURL, nil) + } + + res, err := testRefresh(t, &refreshedToken, ts.URL, false) + require.NoError(t, err) + assert.Equal(t, http.StatusOK, res.StatusCode) + + body, err := io.ReadAll(res.Body) + require.NoError(t, err) + require.NoError(t, json.Unmarshal(body, &refreshedToken)) + + accessTokenClaims := testhelpers.IntrospectToken(t, oauthConfig, refreshedToken.AccessToken, ts) + require.Equal(t, accessTokenClaims.Get("ext.hooked").String(), hookType) + + idTokenBody, err := x.DecodeSegment( + strings.Split( + gjson.GetBytes(body, "id_token").String(), + ".", + )[1], + ) + require.NoError(t, err) + + require.Equal(t, gjson.GetBytes(idTokenBody, "hooked").String(), hookType) } - - w.WriteHeader(http.StatusOK) - require.NoError(t, json.NewEncoder(w).Encode(&hookResp)) - })) - defer hs.Close() - - conf.MustSet(ctx, config.KeyRefreshTokenHookURL, hs.URL) - defer conf.MustSet(ctx, config.KeyRefreshTokenHookURL, nil) - - res, err := testRefresh(t, &refreshedToken, ts.URL, false) - require.NoError(t, err) - assert.Equal(t, http.StatusOK, res.StatusCode) - - body, err := io.ReadAll(res.Body) - require.NoError(t, err) - require.NoError(t, json.Unmarshal(body, &refreshedToken)) - - accessTokenClaims := testhelpers.IntrospectToken(t, oauthConfig, refreshedToken.AccessToken, ts) - require.True(t, accessTokenClaims.Get("ext.hooked").Bool()) - - idTokenBody, err := x.DecodeSegment( - strings.Split( - gjson.GetBytes(body, "id_token").String(), - ".", - )[1], - ) - require.NoError(t, err) - - require.True(t, gjson.GetBytes(idTokenBody, "hooked").Bool()) + } + t.Run("hook=legacy", run("legacy")) + t.Run("hook=new", run("new")) }) t.Run("should not override session data if token refresh hook returns no content", func(t *testing.T) { - hs := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusNoContent) - })) - defer hs.Close() - - conf.MustSet(ctx, config.KeyRefreshTokenHookURL, hs.URL) - defer conf.MustSet(ctx, config.KeyRefreshTokenHookURL, nil) - - origAccessTokenClaims := testhelpers.IntrospectToken(t, oauthConfig, refreshedToken.AccessToken, ts) - - res, err := testRefresh(t, &refreshedToken, ts.URL, false) - require.NoError(t, err) - assert.Equal(t, http.StatusOK, res.StatusCode) - - body, err = io.ReadAll(res.Body) - require.NoError(t, err) - - require.NoError(t, json.Unmarshal(body, &refreshedToken)) - - refreshedAccessTokenClaims := testhelpers.IntrospectToken(t, oauthConfig, refreshedToken.AccessToken, ts) - assertx.EqualAsJSONExcept(t, json.RawMessage(origAccessTokenClaims.Raw), json.RawMessage(refreshedAccessTokenClaims.Raw), []string{"exp", "iat", "nbf"}) + run := func(hookType string) func(t *testing.T) { + return func(t *testing.T) { + hs := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusNoContent) + })) + defer hs.Close() + + if hookType == "legacy" { + conf.MustSet(ctx, config.KeyRefreshTokenHookURL, hs.URL) + defer conf.MustSet(ctx, config.KeyRefreshTokenHookURL, nil) + } else { + conf.MustSet(ctx, config.KeyTokenHookURL, hs.URL) + defer conf.MustSet(ctx, config.KeyTokenHookURL, nil) + } + + origAccessTokenClaims := testhelpers.IntrospectToken(t, oauthConfig, refreshedToken.AccessToken, ts) + + res, err := testRefresh(t, &refreshedToken, ts.URL, false) + require.NoError(t, err) + assert.Equal(t, http.StatusOK, res.StatusCode) + + body, err = io.ReadAll(res.Body) + require.NoError(t, err) + + require.NoError(t, json.Unmarshal(body, &refreshedToken)) + + refreshedAccessTokenClaims := testhelpers.IntrospectToken(t, oauthConfig, refreshedToken.AccessToken, ts) + assertx.EqualAsJSONExcept(t, json.RawMessage(origAccessTokenClaims.Raw), json.RawMessage(refreshedAccessTokenClaims.Raw), []string{"exp", "iat", "nbf"}) + } + } + t.Run("hook=legacy", run("legacy")) + t.Run("hook=new", run("new")) }) - t.Run("should fail token refresh with `server_error` if hook fails", func(t *testing.T) { - hs := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusInternalServerError) - })) - defer hs.Close() - - conf.MustSet(ctx, config.KeyRefreshTokenHookURL, hs.URL) - defer conf.MustSet(ctx, config.KeyRefreshTokenHookURL, nil) - - res, err := testRefresh(t, &refreshedToken, ts.URL, false) - require.NoError(t, err) - assert.Equal(t, http.StatusInternalServerError, res.StatusCode) - - var errBody fosite.RFC6749ErrorJson - require.NoError(t, json.NewDecoder(res.Body).Decode(&errBody)) - require.Equal(t, fosite.ErrServerError.Error(), errBody.Name) - require.Equal(t, "An error occurred while executing the refresh token hook.", errBody.Description) + t.Run("should fail token refresh with `server_error` if refresh hook fails", func(t *testing.T) { + run := func(hookType string) func(t *testing.T) { + return func(t *testing.T) { + hs := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusInternalServerError) + })) + defer hs.Close() + + if hookType == "legacy" { + conf.MustSet(ctx, config.KeyRefreshTokenHookURL, hs.URL) + defer conf.MustSet(ctx, config.KeyRefreshTokenHookURL, nil) + } else { + conf.MustSet(ctx, config.KeyTokenHookURL, hs.URL) + defer conf.MustSet(ctx, config.KeyTokenHookURL, nil) + } + + res, err := testRefresh(t, &refreshedToken, ts.URL, false) + require.NoError(t, err) + assert.Equal(t, http.StatusInternalServerError, res.StatusCode) + + var errBody fosite.RFC6749ErrorJson + require.NoError(t, json.NewDecoder(res.Body).Decode(&errBody)) + require.Equal(t, fosite.ErrServerError.Error(), errBody.Name) + require.Equal(t, "An error occurred while executing the token hook.", errBody.Description) + } + } + t.Run("hook=legacy", run("legacy")) + t.Run("hook=new", run("new")) }) - t.Run("should fail token refresh with `access_denied` if hook denied the request", func(t *testing.T) { - hs := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusForbidden) - })) - defer hs.Close() - - conf.MustSet(ctx, config.KeyRefreshTokenHookURL, hs.URL) - defer conf.MustSet(ctx, config.KeyRefreshTokenHookURL, nil) - - res, err := testRefresh(t, &refreshedToken, ts.URL, false) - require.NoError(t, err) - assert.Equal(t, http.StatusForbidden, res.StatusCode) - - var errBody fosite.RFC6749ErrorJson - require.NoError(t, json.NewDecoder(res.Body).Decode(&errBody)) - require.Equal(t, fosite.ErrAccessDenied.Error(), errBody.Name) - require.Equal(t, "The refresh token hook target responded with an error. Make sure that the request you are making is valid. Maybe the credential or request parameters you are using are limited in scope or otherwise restricted.", errBody.Description) + t.Run("should fail token refresh with `access_denied` if legacy refresh hook denied the request", func(t *testing.T) { + run := func(hookType string) func(t *testing.T) { + return func(t *testing.T) { + hs := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusForbidden) + })) + defer hs.Close() + + if hookType == "legacy" { + conf.MustSet(ctx, config.KeyRefreshTokenHookURL, hs.URL) + defer conf.MustSet(ctx, config.KeyRefreshTokenHookURL, nil) + } else { + conf.MustSet(ctx, config.KeyTokenHookURL, hs.URL) + defer conf.MustSet(ctx, config.KeyTokenHookURL, nil) + } + + res, err := testRefresh(t, &refreshedToken, ts.URL, false) + require.NoError(t, err) + assert.Equal(t, http.StatusForbidden, res.StatusCode) + + var errBody fosite.RFC6749ErrorJson + require.NoError(t, json.NewDecoder(res.Body).Decode(&errBody)) + require.Equal(t, fosite.ErrAccessDenied.Error(), errBody.Name) + require.Equal(t, "The token hook target responded with an error. Make sure that the request you are making is valid. Maybe the credential or request parameters you are using are limited in scope or otherwise restricted.", errBody.Description) + } + } + t.Run("hook=legacy", run("legacy")) + t.Run("hook=new", run("new")) }) - t.Run("should fail token refresh with `server_error` if hook response is malformed", func(t *testing.T) { - hs := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusOK) - })) - defer hs.Close() - - conf.MustSet(ctx, config.KeyRefreshTokenHookURL, hs.URL) - defer conf.MustSet(ctx, config.KeyRefreshTokenHookURL, nil) - - res, err := testRefresh(t, &refreshedToken, ts.URL, false) - require.NoError(t, err) - assert.Equal(t, http.StatusInternalServerError, res.StatusCode) - - var errBody fosite.RFC6749ErrorJson - require.NoError(t, json.NewDecoder(res.Body).Decode(&errBody)) - require.Equal(t, fosite.ErrServerError.Error(), errBody.Name) - require.Equal(t, "The refresh token hook target responded with an error.", errBody.Description) + t.Run("should fail token refresh with `server_error` if refresh hook response is malformed", func(t *testing.T) { + run := func(hookType string) func(t *testing.T) { + return func(t *testing.T) { + hs := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusOK) + })) + defer hs.Close() + + if hookType == "legacy" { + conf.MustSet(ctx, config.KeyRefreshTokenHookURL, hs.URL) + defer conf.MustSet(ctx, config.KeyRefreshTokenHookURL, nil) + } else { + conf.MustSet(ctx, config.KeyTokenHookURL, hs.URL) + defer conf.MustSet(ctx, config.KeyTokenHookURL, nil) + } + + res, err := testRefresh(t, &refreshedToken, ts.URL, false) + require.NoError(t, err) + assert.Equal(t, http.StatusInternalServerError, res.StatusCode) + + var errBody fosite.RFC6749ErrorJson + require.NoError(t, json.NewDecoder(res.Body).Decode(&errBody)) + require.Equal(t, fosite.ErrServerError.Error(), errBody.Name) + require.Equal(t, "The token hook target responded with an error.", errBody.Description) + } + } + t.Run("hook=legacy", run("legacy")) + t.Run("hook=new", run("new")) }) t.Run("refreshing old token should no longer work", func(t *testing.T) { diff --git a/oauth2/oauth2_client_credentials_test.go b/oauth2/oauth2_client_credentials_test.go index b151f267679..1703bda9c38 100644 --- a/oauth2/oauth2_client_credentials_test.go +++ b/oauth2/oauth2_client_credentials_test.go @@ -7,6 +7,8 @@ import ( "context" "encoding/json" "math" + "net/http" + "net/http/httptest" "net/url" "strings" "testing" @@ -20,7 +22,9 @@ import ( goauth2 "golang.org/x/oauth2" "golang.org/x/oauth2/clientcredentials" + "github.com/ory/hydra/v2/consent" "github.com/ory/hydra/v2/internal/testhelpers" + hydraoauth2 "github.com/ory/hydra/v2/oauth2" "github.com/ory/x/contextx" hc "github.com/ory/hydra/v2/client" @@ -75,7 +79,7 @@ func TestClientCredentials(t *testing.T) { return string(out) } - var inspectToken = func(t *testing.T, token *goauth2.Token, cl *hc.Client, conf clientcredentials.Config, strategy string, expectedExp time.Time) { + var inspectToken = func(t *testing.T, token *goauth2.Token, cl *hc.Client, conf clientcredentials.Config, strategy string, expectedExp time.Time, checkExtraClaims bool) { introspection := testhelpers.IntrospectToken(t, &goauth2.Config{ClientID: cl.GetID(), ClientSecret: conf.ClientSecret}, token.AccessToken, admin) check := func(res gjson.Result) { @@ -87,6 +91,10 @@ func TestClientCredentials(t *testing.T) { requirex.EqualTime(t, expectedExp, time.Unix(res.Get("exp").Int(), 0), time.Second) assert.EqualValues(t, encodeOr(t, conf.EndpointParams["audience"], "[]"), res.Get("aud").Raw, "%s", res.Raw) + + if checkExtraClaims { + require.True(t, res.Get("ext.hooked").Bool()) + } } check(introspection) @@ -108,10 +116,10 @@ func TestClientCredentials(t *testing.T) { check(jwtClaims) } - var getAndInspectToken = func(t *testing.T, cl *hc.Client, conf clientcredentials.Config, strategy string, expectedExp time.Time) { + var getAndInspectToken = func(t *testing.T, cl *hc.Client, conf clientcredentials.Config, strategy string, expectedExp time.Time, checkExtraClaims bool) { token, err := getToken(t, conf) require.NoError(t, err) - inspectToken(t, token, cl, conf, strategy, expectedExp) + inspectToken(t, token, cl, conf, strategy, expectedExp, checkExtraClaims) } t.Run("case=should fail because audience is not allowed", func(t *testing.T) { @@ -134,7 +142,7 @@ func TestClientCredentials(t *testing.T) { reg.Config().MustSet(ctx, config.KeyAccessTokenStrategy, strategy) cl, conf := newClient(t) - getAndInspectToken(t, cl, conf, strategy, time.Now().Add(reg.Config().GetAccessTokenLifespan(ctx))) + getAndInspectToken(t, cl, conf, strategy, time.Now().Add(reg.Config().GetAccessTokenLifespan(ctx)), false) } } @@ -149,7 +157,7 @@ func TestClientCredentials(t *testing.T) { cl, conf := newClient(t) conf.EndpointParams = url.Values{} - getAndInspectToken(t, cl, conf, strategy, time.Now().Add(reg.Config().GetAccessTokenLifespan(ctx))) + getAndInspectToken(t, cl, conf, strategy, time.Now().Add(reg.Config().GetAccessTokenLifespan(ctx)), false) } } @@ -164,7 +172,7 @@ func TestClientCredentials(t *testing.T) { cl, conf := newClient(t) conf.Scopes = []string{} - getAndInspectToken(t, cl, conf, strategy, time.Now().Add(reg.Config().GetAccessTokenLifespan(ctx))) + getAndInspectToken(t, cl, conf, strategy, time.Now().Add(reg.Config().GetAccessTokenLifespan(ctx)), false) } } @@ -188,7 +196,7 @@ func TestClientCredentials(t *testing.T) { // We reset this so that introspectToken is going to check for the default scope. conf.Scopes = defaultScope - inspectToken(t, token, cl, conf, strategy, time.Now().Add(reg.Config().GetAccessTokenLifespan(ctx))) + inspectToken(t, token, cl, conf, strategy, time.Now().Add(reg.Config().GetAccessTokenLifespan(ctx)), false) } } @@ -211,7 +219,7 @@ func TestClientCredentials(t *testing.T) { Audience: []string{"https://api.ory.sh/"}, }) testhelpers.UpdateClientTokenLifespans(t, &goauth2.Config{ClientID: cl.GetID(), ClientSecret: conf.ClientSecret}, cl.GetID(), testhelpers.TestLifespans, admin) - getAndInspectToken(t, cl, conf, strategy, time.Now().Add(testhelpers.TestLifespans.ClientCredentialsGrantAccessTokenLifespan.Duration)) + getAndInspectToken(t, cl, conf, strategy, time.Now().Add(testhelpers.TestLifespans.ClientCredentialsGrantAccessTokenLifespan.Duration), false) } } @@ -241,4 +249,135 @@ func TestClientCredentials(t *testing.T) { t.Run("strategy=opaque", run("opaque")) t.Run("strategy=jwt", run("jwt")) }) + + t.Run("should call token hook if configured", func(t *testing.T) { + run := func(strategy string) func(t *testing.T) { + return func(t *testing.T) { + scope := "foobar" + audience := []string{"https://api.ory.sh/"} + + hs := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + assert.Equal(t, r.Header.Get("Content-Type"), "application/json; charset=UTF-8") + + expectedGrantedScopes := []string{"foobar"} + expectedGrantedAudience := []string{"https://api.ory.sh/"} + + var hookReq hydraoauth2.TokenHookRequest + require.NoError(t, json.NewDecoder(r.Body).Decode(&hookReq)) + require.NotEmpty(t, hookReq.Session) + require.Equal(t, hookReq.Session.Extra, map[string]interface{}{}) + require.NotEmpty(t, hookReq.Request) + require.ElementsMatch(t, hookReq.Request.GrantedScopes, expectedGrantedScopes) + require.ElementsMatch(t, hookReq.Request.GrantedAudience, expectedGrantedAudience) + require.Equal(t, hookReq.Request.Payload, map[string][]string{}) + + claims := map[string]interface{}{ + "hooked": true, + } + + hookResp := hydraoauth2.TokenHookResponse{ + Session: consent.AcceptOAuth2ConsentRequestSession{ + AccessToken: claims, + IDToken: claims, + }, + } + + w.WriteHeader(http.StatusOK) + require.NoError(t, json.NewEncoder(w).Encode(&hookResp)) + })) + defer hs.Close() + + reg.Config().MustSet(ctx, config.KeyAccessTokenStrategy, strategy) + reg.Config().MustSet(ctx, config.KeyTokenHookURL, hs.URL) + + defer reg.Config().MustSet(ctx, config.KeyTokenHookURL, nil) + + secret := uuid.New().String() + cl, conf := newCustomClient(t, &hc.Client{ + Secret: secret, + RedirectURIs: []string{public.URL + "/callback"}, + ResponseTypes: []string{"token"}, + GrantTypes: []string{"client_credentials"}, + Scope: scope, + Audience: audience, + }) + getAndInspectToken(t, cl, conf, strategy, time.Now().Add(reg.Config().GetAccessTokenLifespan(ctx)), true) + } + } + + t.Run("strategy=opaque", run("opaque")) + t.Run("strategy=jwt", run("jwt")) + }) + + t.Run("should fail token if hook fails", func(t *testing.T) { + run := func(strategy string) func(t *testing.T) { + return func(t *testing.T) { + hs := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusInternalServerError) + })) + defer hs.Close() + + reg.Config().MustSet(ctx, config.KeyAccessTokenStrategy, strategy) + reg.Config().MustSet(ctx, config.KeyTokenHookURL, hs.URL) + + defer reg.Config().MustSet(ctx, config.KeyTokenHookURL, nil) + + _, conf := newClient(t) + + _, err := getToken(t, conf) + require.Error(t, err) + } + } + + t.Run("strategy=opaque", run("opaque")) + t.Run("strategy=jwt", run("jwt")) + }) + + t.Run("should fail token if hook denied the request", func(t *testing.T) { + run := func(strategy string) func(t *testing.T) { + return func(t *testing.T) { + hs := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusForbidden) + })) + defer hs.Close() + + reg.Config().MustSet(ctx, config.KeyAccessTokenStrategy, strategy) + reg.Config().MustSet(ctx, config.KeyTokenHookURL, hs.URL) + + defer reg.Config().MustSet(ctx, config.KeyTokenHookURL, nil) + + _, conf := newClient(t) + + _, err := getToken(t, conf) + require.Error(t, err) + } + } + + t.Run("strategy=opaque", run("opaque")) + t.Run("strategy=jwt", run("jwt")) + }) + + t.Run("should fail token if hook response is malformed", func(t *testing.T) { + run := func(strategy string) func(t *testing.T) { + return func(t *testing.T) { + hs := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusOK) + })) + defer hs.Close() + + reg.Config().MustSet(ctx, config.KeyAccessTokenStrategy, strategy) + reg.Config().MustSet(ctx, config.KeyTokenHookURL, hs.URL) + + defer reg.Config().MustSet(ctx, config.KeyTokenHookURL, nil) + + _, conf := newClient(t) + + _, err := getToken(t, conf) + require.Error(t, err) + } + } + + t.Run("strategy=opaque", run("opaque")) + t.Run("strategy=jwt", run("jwt")) + }) } diff --git a/oauth2/oauth2_jwt_bearer_test.go b/oauth2/oauth2_jwt_bearer_test.go index d77e8d5a9ff..1aa1f8179ff 100644 --- a/oauth2/oauth2_jwt_bearer_test.go +++ b/oauth2/oauth2_jwt_bearer_test.go @@ -9,6 +9,7 @@ import ( "fmt" "io" "net/http" + "net/http/httptest" "net/url" "strings" "testing" @@ -19,7 +20,9 @@ import ( "gopkg.in/square/go-jose.v2" "github.com/ory/fosite/token/jwt" + "github.com/ory/hydra/v2/consent" "github.com/ory/hydra/v2/jwk" + hydraoauth2 "github.com/ory/hydra/v2/oauth2" "github.com/ory/hydra/v2/oauth2/trust" "github.com/stretchr/testify/assert" @@ -61,11 +64,13 @@ func TestJWTBearer(t *testing.T) { } var getToken = func(t *testing.T, conf *clientcredentials.Config) (*goauth2.Token, error) { - conf.AuthStyle = goauth2.AuthStyleInHeader + if conf.AuthStyle == goauth2.AuthStyleAutoDetect { + conf.AuthStyle = goauth2.AuthStyleInHeader + } return conf.Token(context.Background()) } - var inspectToken = func(t *testing.T, token *goauth2.Token, cl *hc.Client, strategy string, grant trust.Grant) { + var inspectToken = func(t *testing.T, token *goauth2.Token, cl *hc.Client, strategy string, grant trust.Grant, checkExtraClaims bool) { introspection := testhelpers.IntrospectToken(t, &goauth2.Config{ClientID: cl.GetID(), ClientSecret: cl.Secret}, token.AccessToken, admin) check := func(res gjson.Result) { @@ -77,6 +82,10 @@ func TestJWTBearer(t *testing.T) { assert.True(t, res.Get("exp").Int() >= res.Get("iat").Int()+int64(reg.Config().GetAccessTokenLifespan(ctx).Seconds()), "%s", res.Raw) assert.EqualValues(t, fmt.Sprintf(`["%s"]`, reg.Config().OAuth2TokenURL(ctx).String()), res.Get("aud").Raw, "%s", res.Raw) + + if checkExtraClaims { + require.True(t, res.Get("ext.hooked").Bool()) + } } check(introspection) @@ -248,7 +257,7 @@ func TestJWTBearer(t *testing.T) { result, err := getToken(t, conf) require.NoError(t, err) - inspectToken(t, result, client, strategy, trustGrant) + inspectToken(t, result, client, strategy, trustGrant, false) } } @@ -288,7 +297,255 @@ func TestJWTBearer(t *testing.T) { require.NoError(t, json.Unmarshal(body, &result)) assert.NotEmpty(t, result.AccessToken, "%s", body) - inspectToken(t, &result, client, strategy, trustGrant) + inspectToken(t, &result, client, strategy, trustGrant, false) + } + } + + t.Run("strategy=opaque", run("opaque")) + t.Run("strategy=jwt", run("jwt")) + }) + + t.Run("should call token hook if configured", func(t *testing.T) { + run := func(strategy string) func(t *testing.T) { + return func(t *testing.T) { + audience := reg.Config().OAuth2TokenURL(ctx).String() + grantType := "urn:ietf:params:oauth:grant-type:jwt-bearer" + + token, _, err := signer.Generate(ctx, jwt.MapClaims{ + "jti": uuid.NewString(), + "iss": trustGrant.Issuer, + "sub": trustGrant.Subject, + "aud": audience, + "exp": time.Now().Add(time.Hour).Unix(), + "iat": time.Now().Add(-time.Minute).Unix(), + }, &jwt.Headers{Extra: map[string]interface{}{"kid": kid}}) + require.NoError(t, err) + + hs := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + assert.Equal(t, r.Header.Get("Content-Type"), "application/json; charset=UTF-8") + + expectedGrantedScopes := []string{client.Scope} + expectedGrantedAudience := []string{audience} + expectedPayload := map[string][]string(map[string][]string{"assertion": {token}}) + + var hookReq hydraoauth2.TokenHookRequest + require.NoError(t, json.NewDecoder(r.Body).Decode(&hookReq)) + require.NotEmpty(t, hookReq.Session) + require.Equal(t, hookReq.Session.Extra, map[string]interface{}{}) + require.NotEmpty(t, hookReq.Request) + require.ElementsMatch(t, hookReq.Request.GrantedScopes, expectedGrantedScopes) + require.ElementsMatch(t, hookReq.Request.GrantedAudience, expectedGrantedAudience) + require.Equal(t, hookReq.Request.Payload, expectedPayload) + + claims := map[string]interface{}{ + "hooked": true, + } + + hookResp := hydraoauth2.TokenHookResponse{ + Session: consent.AcceptOAuth2ConsentRequestSession{ + AccessToken: claims, + IDToken: claims, + }, + } + + w.WriteHeader(http.StatusOK) + require.NoError(t, json.NewEncoder(w).Encode(&hookResp)) + })) + defer hs.Close() + + reg.Config().MustSet(ctx, config.KeyAccessTokenStrategy, strategy) + reg.Config().MustSet(ctx, config.KeyTokenHookURL, hs.URL) + + defer reg.Config().MustSet(ctx, config.KeyTokenHookURL, nil) + + conf := newConf(client) + conf.EndpointParams = url.Values{"grant_type": {grantType}, "assertion": {token}} + + result, err := getToken(t, conf) + require.NoError(t, err) + + inspectToken(t, result, client, strategy, trustGrant, true) + } + } + + t.Run("strategy=opaque", run("opaque")) + t.Run("strategy=jwt", run("jwt")) + }) + + t.Run("should call token hook if configured and omit client_secret from payload", func(t *testing.T) { + run := func(strategy string) func(t *testing.T) { + return func(t *testing.T) { + audience := reg.Config().OAuth2TokenURL(ctx).String() + grantType := "urn:ietf:params:oauth:grant-type:jwt-bearer" + + token, _, err := signer.Generate(ctx, jwt.MapClaims{ + "jti": uuid.NewString(), + "iss": trustGrant.Issuer, + "sub": trustGrant.Subject, + "aud": audience, + "exp": time.Now().Add(time.Hour).Unix(), + "iat": time.Now().Add(-time.Minute).Unix(), + }, &jwt.Headers{Extra: map[string]interface{}{"kid": kid}}) + require.NoError(t, err) + + client := &hc.Client{ + Secret: secret, + GrantTypes: []string{"urn:ietf:params:oauth:grant-type:jwt-bearer"}, + Scope: "offline_access", + TokenEndpointAuthMethod: "client_secret_post", + } + require.NoError(t, reg.ClientManager().CreateClient(ctx, client)) + + hs := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + assert.Equal(t, r.Header.Get("Content-Type"), "application/json; charset=UTF-8") + + expectedGrantedScopes := []string{client.Scope} + expectedGrantedAudience := []string{audience} + expectedPayload := map[string][]string(map[string][]string{"assertion": {token}}) + + var hookReq hydraoauth2.TokenHookRequest + require.NoError(t, json.NewDecoder(r.Body).Decode(&hookReq)) + require.NotEmpty(t, hookReq.Session) + require.Equal(t, hookReq.Session.Extra, map[string]interface{}{}) + require.NotEmpty(t, hookReq.Request) + require.ElementsMatch(t, hookReq.Request.GrantedScopes, expectedGrantedScopes) + require.ElementsMatch(t, hookReq.Request.GrantedAudience, expectedGrantedAudience) + require.Equal(t, hookReq.Request.Payload, expectedPayload) + + claims := map[string]interface{}{ + "hooked": true, + } + + hookResp := hydraoauth2.TokenHookResponse{ + Session: consent.AcceptOAuth2ConsentRequestSession{ + AccessToken: claims, + IDToken: claims, + }, + } + + w.WriteHeader(http.StatusOK) + require.NoError(t, json.NewEncoder(w).Encode(&hookResp)) + })) + defer hs.Close() + + reg.Config().MustSet(ctx, config.KeyAccessTokenStrategy, strategy) + reg.Config().MustSet(ctx, config.KeyTokenHookURL, hs.URL) + + defer reg.Config().MustSet(ctx, config.KeyTokenHookURL, nil) + + conf := newConf(client) + conf.AuthStyle = goauth2.AuthStyleInParams + conf.EndpointParams = url.Values{"grant_type": {grantType}, "assertion": {token}} + + result, err := getToken(t, conf) + require.NoError(t, err) + + inspectToken(t, result, client, strategy, trustGrant, true) + } + } + + t.Run("strategy=opaque", run("opaque")) + t.Run("strategy=jwt", run("jwt")) + }) + + t.Run("should fail token if hook fails", func(t *testing.T) { + run := func(strategy string) func(t *testing.T) { + return func(t *testing.T) { + hs := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusInternalServerError) + })) + defer hs.Close() + + reg.Config().MustSet(ctx, config.KeyAccessTokenStrategy, strategy) + reg.Config().MustSet(ctx, config.KeyTokenHookURL, hs.URL) + + defer reg.Config().MustSet(ctx, config.KeyTokenHookURL, nil) + + token, _, err := signer.Generate(ctx, jwt.MapClaims{ + "jti": uuid.NewString(), + "iss": trustGrant.Issuer, + "sub": trustGrant.Subject, + "aud": reg.Config().OAuth2TokenURL(ctx).String(), + "exp": time.Now().Add(time.Hour).Unix(), + "iat": time.Now().Add(-time.Minute).Unix(), + }, &jwt.Headers{Extra: map[string]interface{}{"kid": kid}}) + require.NoError(t, err) + + conf := newConf(client) + conf.EndpointParams = url.Values{"grant_type": {"urn:ietf:params:oauth:grant-type:jwt-bearer"}, "assertion": {token}} + + _, tokenError := getToken(t, conf) + require.Error(t, tokenError) + } + } + + t.Run("strategy=opaque", run("opaque")) + t.Run("strategy=jwt", run("jwt")) + }) + + t.Run("should fail token if hook denied the request", func(t *testing.T) { + run := func(strategy string) func(t *testing.T) { + return func(t *testing.T) { + hs := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusForbidden) + })) + defer hs.Close() + + reg.Config().MustSet(ctx, config.KeyAccessTokenStrategy, strategy) + reg.Config().MustSet(ctx, config.KeyTokenHookURL, hs.URL) + + defer reg.Config().MustSet(ctx, config.KeyTokenHookURL, nil) + + token, _, err := signer.Generate(ctx, jwt.MapClaims{ + "jti": uuid.NewString(), + "iss": trustGrant.Issuer, + "sub": trustGrant.Subject, + "aud": reg.Config().OAuth2TokenURL(ctx).String(), + "exp": time.Now().Add(time.Hour).Unix(), + "iat": time.Now().Add(-time.Minute).Unix(), + }, &jwt.Headers{Extra: map[string]interface{}{"kid": kid}}) + require.NoError(t, err) + + conf := newConf(client) + conf.EndpointParams = url.Values{"grant_type": {"urn:ietf:params:oauth:grant-type:jwt-bearer"}, "assertion": {token}} + + _, tokenError := getToken(t, conf) + require.Error(t, tokenError) + } + } + + t.Run("strategy=opaque", run("opaque")) + t.Run("strategy=jwt", run("jwt")) + }) + + t.Run("should fail token if hook response is malformed", func(t *testing.T) { + run := func(strategy string) func(t *testing.T) { + return func(t *testing.T) { + hs := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusOK) + })) + defer hs.Close() + + reg.Config().MustSet(ctx, config.KeyAccessTokenStrategy, strategy) + reg.Config().MustSet(ctx, config.KeyTokenHookURL, hs.URL) + + defer reg.Config().MustSet(ctx, config.KeyTokenHookURL, nil) + + token, _, err := signer.Generate(ctx, jwt.MapClaims{ + "jti": uuid.NewString(), + "iss": trustGrant.Issuer, + "sub": trustGrant.Subject, + "aud": reg.Config().OAuth2TokenURL(ctx).String(), + "exp": time.Now().Add(time.Hour).Unix(), + "iat": time.Now().Add(-time.Minute).Unix(), + }, &jwt.Headers{Extra: map[string]interface{}{"kid": kid}}) + require.NoError(t, err) + + conf := newConf(client) + conf.EndpointParams = url.Values{"grant_type": {"urn:ietf:params:oauth:grant-type:jwt-bearer"}, "assertion": {token}} + + _, tokenError := getToken(t, conf) + require.Error(t, tokenError) } } diff --git a/oauth2/hook.go b/oauth2/refresh_hook.go similarity index 50% rename from oauth2/hook.go rename to oauth2/refresh_hook.go index e46add43b6c..62997a2f0f5 100644 --- a/oauth2/hook.go +++ b/oauth2/refresh_hook.go @@ -4,24 +4,16 @@ package oauth2 import ( - "bytes" "context" "encoding/json" - "net/http" - - "github.com/hashicorp/go-retryablehttp" "github.com/ory/hydra/v2/x" + "github.com/ory/x/errorsx" "github.com/ory/fosite" - "github.com/ory/hydra/v2/consent" "github.com/ory/hydra/v2/driver/config" - "github.com/ory/x/errorsx" ) -// AccessRequestHook is called when an access token is being refreshed. -type AccessRequestHook func(ctx context.Context, requester fosite.AccessRequester) error - // Requester is a token endpoint's request context. // // swagger:ignore @@ -54,14 +46,6 @@ type RefreshTokenHookRequest struct { GrantedAudience []string `json:"granted_audience"` } -// RefreshTokenHookResponse is the response body received from the refresh token hook. -// -// swagger:ignore -type RefreshTokenHookResponse struct { - // Session is the session data returned by the hook. - Session consent.AcceptOAuth2ConsentRequestSession `json:"session"` -} - // RefreshTokenHook is an AccessRequestHook called for `refresh_token` grant type. func RefreshTokenHook(reg interface { config.Provider @@ -97,72 +81,22 @@ func RefreshTokenHook(reg interface { GrantedScopes: requester.GetGrantedScopes(), GrantedAudience: requester.GetGrantedAudience(), } - reqBodyBytes, err := json.Marshal(&reqBody) - if err != nil { - return errorsx.WithStack( - fosite.ErrServerError. - WithWrap(err). - WithDescription("An error occurred while encoding the refresh token hook."). - WithDebugf("Unable to encode the refresh token hook body: %s", err), - ) - } - req, err := retryablehttp.NewRequestWithContext(ctx, http.MethodPost, hookURL.String(), bytes.NewReader(reqBodyBytes)) + reqBodyBytes, err := json.Marshal(&reqBody) if err != nil { return errorsx.WithStack( fosite.ErrServerError. WithWrap(err). - WithDescription("An error occurred while preparing the refresh token hook."). - WithDebugf("Unable to prepare the HTTP Request: %s", err), + WithDescription("An error occurred while encoding the token hook."). + WithDebugf("Unable to encode the token hook body: %s", err), ) } - req.Header.Set("Content-Type", "application/json; charset=UTF-8") - resp, err := reg.HTTPClient(ctx).Do(req) + err = executeHookAndUpdateSession(ctx, reg, hookURL, reqBodyBytes, session) if err != nil { - return errorsx.WithStack( - fosite.ErrServerError. - WithWrap(err). - WithDescription("An error occurred while executing the refresh token hook."). - WithDebugf("Unable to execute HTTP Request: %s", err), - ) - } - defer resp.Body.Close() - - switch resp.StatusCode { - case http.StatusOK: - // Token refresh permitted with new session data - case http.StatusNoContent: - // Token refresh is permitted without overriding session data - return nil - case http.StatusForbidden: - return errorsx.WithStack( - fosite.ErrAccessDenied. - WithDescription("The refresh token hook target responded with an error."). - WithDebugf("Refresh token hook responded with HTTP status code: %s", resp.Status), - ) - default: - return errorsx.WithStack( - fosite.ErrServerError. - WithDescription("The refresh token hook target responded with an error."). - WithDebugf("Refresh token hook responded with HTTP status code: %s", resp.Status), - ) - } - - var respBody RefreshTokenHookResponse - if err := json.NewDecoder(resp.Body).Decode(&respBody); err != nil { - return errorsx.WithStack( - fosite.ErrServerError. - WithWrap(err). - WithDescription("The refresh token hook target responded with an error."). - WithDebugf("Response from refresh token hook could not be decoded: %s", err), - ) + return err } - // Overwrite existing session data (extra claims). - session.Extra = respBody.Session.AccessToken - idTokenClaims := session.IDTokenClaims() - idTokenClaims.Extra = respBody.Session.IDToken return nil } } diff --git a/oauth2/token_hook.go b/oauth2/token_hook.go new file mode 100644 index 00000000000..f7ca4416a71 --- /dev/null +++ b/oauth2/token_hook.go @@ -0,0 +1,166 @@ +// Copyright © 2022 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package oauth2 + +import ( + "bytes" + "context" + "encoding/json" + "net/http" + "net/url" + + "github.com/hashicorp/go-retryablehttp" + + "github.com/ory/hydra/v2/x" + + "github.com/ory/fosite" + "github.com/ory/hydra/v2/consent" + "github.com/ory/hydra/v2/driver/config" + "github.com/ory/x/errorsx" +) + +// AccessRequestHook is called when an access token request is performed. +type AccessRequestHook func(ctx context.Context, requester fosite.AccessRequester) error + +// Request is a token endpoint's request context. +// +// swagger:ignore +type Request struct { + // ClientID is the identifier of the OAuth 2.0 client. + ClientID string `json:"client_id"` + // GrantedScopes is the list of scopes granted to the OAuth 2.0 client. + GrantedScopes []string `json:"granted_scopes"` + // GrantedAudience is the list of audiences granted to the OAuth 2.0 client. + GrantedAudience []string `json:"granted_audience"` + // GrantTypes is the requests grant types. + GrantTypes []string `json:"grant_types"` + // Payload is the requests payload. + Payload map[string][]string `json:"payload"` +} + +// TokenHookRequest is the request body sent to the token hook. +// +// swagger:ignore +type TokenHookRequest struct { + // Session is the request's session.. + Session *Session `json:"session"` + // Requester is a token endpoint's request context. + Request Request `json:"request"` +} + +// TokenHookResponse is the response body received from the token hook. +// +// swagger:ignore +type TokenHookResponse struct { + // Session is the session data returned by the hook. + Session consent.AcceptOAuth2ConsentRequestSession `json:"session"` +} + +func executeHookAndUpdateSession(ctx context.Context, reg x.HTTPClientProvider, hookURL *url.URL, reqBodyBytes []byte, session *Session) error { + req, err := retryablehttp.NewRequestWithContext(ctx, http.MethodPost, hookURL.String(), bytes.NewReader(reqBodyBytes)) + if err != nil { + return errorsx.WithStack( + fosite.ErrServerError. + WithWrap(err). + WithDescription("An error occurred while preparing the token hook."). + WithDebugf("Unable to prepare the HTTP Request: %s", err), + ) + } + req.Header.Set("Content-Type", "application/json; charset=UTF-8") + + resp, err := reg.HTTPClient(ctx).Do(req) + if err != nil { + return errorsx.WithStack( + fosite.ErrServerError. + WithWrap(err). + WithDescription("An error occurred while executing the token hook."). + WithDebugf("Unable to execute HTTP Request: %s", err), + ) + } + defer resp.Body.Close() + + switch resp.StatusCode { + case http.StatusOK: + // Token permitted with new session data + case http.StatusNoContent: + // Token is permitted without overriding session data + return nil + case http.StatusForbidden: + return errorsx.WithStack( + fosite.ErrAccessDenied. + WithDescription("The token hook target responded with an error."). + WithDebugf("Token hook responded with HTTP status code: %s", resp.Status), + ) + default: + return errorsx.WithStack( + fosite.ErrServerError. + WithDescription("The token hook target responded with an error."). + WithDebugf("Token hook responded with HTTP status code: %s", resp.Status), + ) + } + + var respBody TokenHookResponse + if err := json.NewDecoder(resp.Body).Decode(&respBody); err != nil { + return errorsx.WithStack( + fosite.ErrServerError. + WithWrap(err). + WithDescription("The token hook target responded with an error."). + WithDebugf("Response from token hook could not be decoded: %s", err), + ) + } + + // Overwrite existing session data (extra claims). + session.Extra = respBody.Session.AccessToken + idTokenClaims := session.IDTokenClaims() + idTokenClaims.Extra = respBody.Session.IDToken + return nil +} + +// TokenHook is an AccessRequestHook called for all grant types. +func TokenHook(reg interface { + config.Provider + x.HTTPClientProvider +}) AccessRequestHook { + return func(ctx context.Context, requester fosite.AccessRequester) error { + hookURL := reg.Config().TokenHookURL(ctx) + if hookURL == nil { + return nil + } + + session, ok := requester.GetSession().(*Session) + if !ok { + return nil + } + + request := Request{ + ClientID: requester.GetClient().GetID(), + GrantedScopes: requester.GetGrantedScopes(), + GrantedAudience: requester.GetGrantedAudience(), + GrantTypes: requester.GetGrantTypes(), + Payload: requester.Sanitize([]string{"assertion"}).GetRequestForm(), + } + + reqBody := TokenHookRequest{ + Session: session, + Request: request, + } + + reqBodyBytes, err := json.Marshal(&reqBody) + if err != nil { + return errorsx.WithStack( + fosite.ErrServerError. + WithWrap(err). + WithDescription("An error occurred while encoding the token hook."). + WithDebugf("Unable to encode the token hook body: %s", err), + ) + } + + err = executeHookAndUpdateSession(ctx, reg, hookURL, reqBodyBytes, session) + if err != nil { + return err + } + + return nil + } +} diff --git a/spec/config.json b/spec/config.json index f2cf7e46299..34c22e26d34 100644 --- a/spec/config.json +++ b/spec/config.json @@ -975,6 +975,12 @@ "description": "Sets the refresh token hook endpoint. If set it will be called during token refresh to receive updated token claims.", "format": "uri", "examples": ["https://my-example.app/token-refresh-hook"] + }, + "token_hook": { + "type": "string", + "description": "Sets the token hook endpoint for all grant types. If set it will be called while providing token to customize claims.", + "format": "uri", + "examples": ["https://my-example.app/token-hook"] } } },