Skip to content

Commit

Permalink
fix: do not generate CSRF token for api flows (#3704)
Browse files Browse the repository at this point in the history
  • Loading branch information
aeneasr authored Jan 19, 2024
1 parent 55560a1 commit d93570d
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
3 changes: 2 additions & 1 deletion selfservice/strategy/code/strategy_recovery.go
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,6 @@ func (s *Strategy) recoveryIssueSession(w http.ResponseWriter, r *http.Request,

f.UI.Messages.Clear()
f.State = flow.StatePassedChallenge
f.SetCSRFToken(s.deps.CSRFHandler().RegenerateToken(w, r))
f.RecoveredIdentityID = uuid.NullUUID{
UUID: id.ID,
Valid: true,
Expand All @@ -191,6 +190,8 @@ func (s *Strategy) recoveryIssueSession(w http.ResponseWriter, r *http.Request,

switch f.Type {
case flow.TypeBrowser:
f.SetCSRFToken(s.deps.CSRFHandler().RegenerateToken(w, r))

if err := s.deps.SessionManager().UpsertAndIssueCookie(ctx, w, r, sess); err != nil {
return s.retryRecoveryFlow(w, r, f.Type, RetryWithError(err))
}
Expand Down
37 changes: 37 additions & 0 deletions selfservice/strategy/code/strategy_recovery_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1574,6 +1574,43 @@ func TestRecovery_WithContinueWith(t *testing.T) {
}
})

t.Run("description=does not issue csrf cookie when submitting API flow", func(t *testing.T) {
t.Run("type="+RecoveryClientTypeAPI.String(), func(t *testing.T) {
c := new(http.Client)
recoveryEmail := testhelpers.RandomEmail()
_ = createIdentityToRecover(t, reg, recoveryEmail)

actual := submitRecoveryForm(t, c, RecoveryClientTypeAPI, func(v url.Values) {
v.Set("email", recoveryEmail)
}, http.StatusOK)

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

action := gjson.Get(actual, "ui.action").String()
require.NotEmpty(t, action)

flowId := gjson.Get(actual, "id").String()
require.NotEmpty(t, flowId)

form := withCSRFToken(t, RecoveryClientTypeAPI, actual, url.Values{
"code": {recoveryCode},
})

// Now submit the correct code
res, err := c.Post(action, "application/json", bytes.NewBufferString(form))
require.NoError(t, err)

assert.Equal(t, http.StatusOK, res.StatusCode)

assert.Empty(t, res.Header.Get("Set-Cookie"))

json := ioutilx.MustReadAll(res.Body)
require.NotEmpty(t, gjson.GetBytes(json, "continue_with.#(action==show_settings_ui).flow").String(), "%s", json)
require.NotEmpty(t, gjson.GetBytes(json, "continue_with.#(action==set_ory_session_token).ory_session_token").String(), "%s", json)
})
})

t.Run("description=should not be able to use an invalid code", func(t *testing.T) {
for _, testCase := range flowTypeCases {
t.Run("type="+testCase.ClientType.String(), func(t *testing.T) {
Expand Down

0 comments on commit d93570d

Please sign in to comment.