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

fix: Run post recovery hook before storing the session and issuing a cookie #3393

Merged
merged 3 commits into from
Aug 21, 2023
Merged
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
8 changes: 4 additions & 4 deletions selfservice/strategy/code/strategy_recovery.go
Original file line number Diff line number Diff line change
Expand Up @@ -373,6 +373,10 @@ func (s *Strategy) recoveryIssueSession(w http.ResponseWriter, r *http.Request,
return s.retryRecoveryFlowWithError(w, r, f.Type, err)
}

if err := s.deps.RecoveryExecutor().PostRecoveryHook(w, r, f, sess); err != nil {
return s.retryRecoveryFlowWithError(w, r, f.Type, err)
}

// TODO: How does this work with Mobile?
if err := s.deps.SessionManager().UpsertAndIssueCookie(ctx, w, r, sess); err != nil {
return s.retryRecoveryFlowWithError(w, r, f.Type, err)
Expand All @@ -393,10 +397,6 @@ func (s *Strategy) recoveryIssueSession(w http.ResponseWriter, r *http.Request,
return s.retryRecoveryFlowWithError(w, r, flow.TypeBrowser, err)
}

if err := s.deps.RecoveryExecutor().PostRecoveryHook(w, r, f, sess); err != nil {
return s.retryRecoveryFlowWithError(w, r, f.Type, err)
}

config := s.deps.Config()

sf.UI.Messages.Set(text.NewRecoverySuccessful(time.Now().Add(config.SelfServiceFlowSettingsPrivilegedSessionMaxAge(ctx))))
Expand Down
66 changes: 66 additions & 0 deletions selfservice/strategy/code/strategy_recovery_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1055,6 +1055,72 @@ func TestRecovery(t *testing.T) {
assert.Empty(t, gjson.Get(body, "ui.nodes.#(attributes.name==code).messages").Array())
testhelpers.AssertMessage(t, []byte(body), "The recovery code is invalid or has already been used. Please try again.")
})

t.Run("description=should recover if post recovery hook is successful", func(t *testing.T) {
conf.MustSet(ctx, config.HookStrategyKey(config.ViperKeySelfServiceRecoveryAfter, config.HookGlobal), []config.SelfServiceHook{{Name: "err", Config: []byte(`{}`)}})
t.Cleanup(func() {
conf.MustSet(ctx, config.HookStrategyKey(config.ViperKeySelfServiceRecoveryAfter, config.HookGlobal), nil)
})

recoveryEmail := testhelpers.RandomEmail()
createIdentityToRecover(t, reg, recoveryEmail)

cl := testhelpers.NewClientWithCookies(t)
body := expectSuccessfulRecovery(t, cl, RecoveryFlowTypeBrowser, func(v url.Values) {
v.Set("email", recoveryEmail)
})

message := testhelpers.CourierExpectMessage(t, reg, recoveryEmail, "Recover access to your account")
recoveryCode := testhelpers.CourierExpectCodeInMessage(t, message, 1)

action := gjson.Get(body, "ui.action").String()
require.NotEmpty(t, action)
assert.Equal(t, recoveryEmail, gjson.Get(body, "ui.nodes.#(attributes.name==email).attributes.value").String())

cl.CheckRedirect = func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
}

body = submitRecoveryCode(t, cl, body, RecoveryFlowTypeBrowser, recoveryCode, http.StatusSeeOther)

require.Len(t, cl.Jar.Cookies(urlx.ParseOrPanic(public.URL)), 2)
cookies := spew.Sdump(cl.Jar.Cookies(urlx.ParseOrPanic(public.URL)))
assert.Contains(t, cookies, "ory_kratos_session")
})

t.Run("description=should not be able to recover if post recovery hook fails", func(t *testing.T) {
conf.MustSet(ctx, config.HookStrategyKey(config.ViperKeySelfServiceRecoveryAfter, config.HookGlobal), []config.SelfServiceHook{{Name: "err", Config: []byte(`{"ExecutePostRecoveryHook": "err"}`)}})
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I couldn't figure out a good way to mock a 4xx response to the webhook request so that I could test the message in the response would show up in the new flow.

t.Cleanup(func() {
conf.MustSet(ctx, config.HookStrategyKey(config.ViperKeySelfServiceRecoveryAfter, config.HookGlobal), nil)
})

recoveryEmail := testhelpers.RandomEmail()
createIdentityToRecover(t, reg, recoveryEmail)

cl := testhelpers.NewClientWithCookies(t)
body := expectSuccessfulRecovery(t, cl, RecoveryFlowTypeBrowser, func(v url.Values) {
v.Set("email", recoveryEmail)
})

message := testhelpers.CourierExpectMessage(t, reg, recoveryEmail, "Recover access to your account")
recoveryCode := testhelpers.CourierExpectCodeInMessage(t, message, 1)

action := gjson.Get(body, "ui.action").String()
require.NotEmpty(t, action)
assert.Equal(t, recoveryEmail, gjson.Get(body, "ui.nodes.#(attributes.name==email).attributes.value").String())

cl.CheckRedirect = func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
}

initialFlowId := gjson.Get(body, "id")
body = submitRecoveryCode(t, cl, body, RecoveryFlowTypeBrowser, recoveryCode, http.StatusSeeOther)
assert.NotEqual(t, gjson.Get(body, "id"), initialFlowId)

require.Len(t, cl.Jar.Cookies(urlx.ParseOrPanic(public.URL)), 1)
cookies := spew.Sdump(cl.Jar.Cookies(urlx.ParseOrPanic(public.URL)))
assert.NotContains(t, cookies, "ory_kratos_session")
})
}

func TestDisabledStrategy(t *testing.T) {
Expand Down
8 changes: 4 additions & 4 deletions selfservice/strategy/link/strategy_recovery.go
Original file line number Diff line number Diff line change
Expand Up @@ -296,6 +296,10 @@ func (s *Strategy) recoveryIssueSession(w http.ResponseWriter, r *http.Request,
return s.retryRecoveryFlowWithError(w, r, flow.TypeBrowser, err)
}

if err := s.d.RecoveryExecutor().PostRecoveryHook(w, r, f, sess); err != nil {
return s.retryRecoveryFlowWithError(w, r, flow.TypeBrowser, err)
}

if err := s.d.SessionManager().UpsertAndIssueCookie(r.Context(), w, r, sess); err != nil {
return s.retryRecoveryFlowWithError(w, r, flow.TypeBrowser, err)
}
Expand All @@ -316,10 +320,6 @@ func (s *Strategy) recoveryIssueSession(w http.ResponseWriter, r *http.Request,
return s.retryRecoveryFlowWithError(w, r, flow.TypeBrowser, err)
}

if err := s.d.RecoveryExecutor().PostRecoveryHook(w, r, f, sess); err != nil {
return s.retryRecoveryFlowWithError(w, r, flow.TypeBrowser, err)
}

sf.UI.Messages.Set(text.NewRecoverySuccessful(time.Now().Add(s.d.Config().SelfServiceFlowSettingsPrivilegedSessionMaxAge(r.Context()))))
if err := s.d.SettingsFlowPersister().UpdateSettingsFlow(r.Context(), sf); err != nil {
return s.retryRecoveryFlowWithError(w, r, flow.TypeBrowser, err)
Expand Down
66 changes: 66 additions & 0 deletions selfservice/strategy/link/strategy_recovery_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -823,6 +823,72 @@ func TestRecovery(t *testing.T) {
assert.Nil(t, addr.VerifiedAt)
assert.Equal(t, identity.VerifiableAddressStatusPending, addr.Status)
})

t.Run("description=should recover if post recovery hook is successful", func(t *testing.T) {
conf.MustSet(ctx, config.HookStrategyKey(config.ViperKeySelfServiceRecoveryAfter, config.HookGlobal), []config.SelfServiceHook{{Name: "err", Config: []byte(`{}`)}})
t.Cleanup(func() {
conf.MustSet(ctx, config.HookStrategyKey(config.ViperKeySelfServiceRecoveryAfter, config.HookGlobal), nil)
})

recoveryEmail := testhelpers.RandomEmail()
createIdentityToRecover(t, reg, recoveryEmail)

var check = func(t *testing.T, actual string) {
message := testhelpers.CourierExpectMessage(t, reg, recoveryEmail, "Recover access to your account")
recoveryLink := testhelpers.CourierExpectLinkInMessage(t, message, 1)

cl := testhelpers.NewClientWithCookies(t)
cl.CheckRedirect = func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
}
res, err := cl.Get(recoveryLink)
require.NoError(t, err)
require.NoError(t, res.Body.Close())
assert.Equal(t, http.StatusSeeOther, res.StatusCode)
require.Len(t, cl.Jar.Cookies(urlx.ParseOrPanic(public.URL)), 2)
cookies := spew.Sdump(cl.Jar.Cookies(urlx.ParseOrPanic(public.URL)))
assert.Contains(t, cookies, "ory_kratos_session")
}

var values = func(v url.Values) {
v.Set("email", recoveryEmail)
}

check(t, expectSuccess(t, nil, false, false, values))
})

t.Run("description=should not be able to recover if post recovery hook fails", func(t *testing.T) {
conf.MustSet(ctx, config.HookStrategyKey(config.ViperKeySelfServiceRecoveryAfter, config.HookGlobal), []config.SelfServiceHook{{Name: "err", Config: []byte(`{"ExecutePostRecoveryHook": "err"}`)}})
t.Cleanup(func() {
conf.MustSet(ctx, config.HookStrategyKey(config.ViperKeySelfServiceRecoveryAfter, config.HookGlobal), nil)
})

recoveryEmail := testhelpers.RandomEmail()
createIdentityToRecover(t, reg, recoveryEmail)

var check = func(t *testing.T, actual string) {
message := testhelpers.CourierExpectMessage(t, reg, recoveryEmail, "Recover access to your account")
recoveryLink := testhelpers.CourierExpectLinkInMessage(t, message, 1)

cl := testhelpers.NewClientWithCookies(t)
cl.CheckRedirect = func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
}
res, err := cl.Get(recoveryLink)
require.NoError(t, err)
require.NoError(t, res.Body.Close())
assert.Equal(t, http.StatusSeeOther, res.StatusCode)
require.Len(t, cl.Jar.Cookies(urlx.ParseOrPanic(public.URL)), 1)
cookies := spew.Sdump(cl.Jar.Cookies(urlx.ParseOrPanic(public.URL)))
assert.NotContains(t, cookies, "ory_kratos_session")
}

var values = func(v url.Values) {
v.Set("email", recoveryEmail)
}

check(t, expectSuccess(t, nil, false, false, values))
})
}

func TestDisabledEndpoint(t *testing.T) {
Expand Down