Skip to content

Commit

Permalink
fix: return correct error in login csrf
Browse files Browse the repository at this point in the history
Closes #785
  • Loading branch information
aeneasr committed Oct 22, 2020
1 parent 76be5b0 commit dd9cab0
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 2 deletions.
2 changes: 1 addition & 1 deletion selfservice/flow/request.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ func VerifyRequest(
return nil
default:
if !nosurf.VerifyToken(generator(r), actual) {
return x.ErrInvalidCSRFToken
return errors.WithStack(x.ErrInvalidCSRFToken)
}
}

Expand Down
2 changes: 1 addition & 1 deletion selfservice/strategy/password/login.go
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ func (s *Strategy) handleLogin(w http.ResponseWriter, r *http.Request, _ httprou
}

if err := flow.VerifyRequest(r, ar.Type, s.d.GenerateCSRFToken, p.CSRFToken); err != nil {
s.handleLoginError(w, r, ar, &p, x.ErrInvalidCSRFToken)
s.handleLoginError(w, r, ar, &p, err)
return
}

Expand Down
37 changes: 37 additions & 0 deletions selfservice/strategy/password/login_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package password_test

import (
"bytes"
"context"
"encoding/json"
"fmt"
Expand Down Expand Up @@ -179,6 +180,42 @@ func TestCompleteLogin(t *testing.T) {
assert.EqualValues(t, http.StatusBadRequest, res.StatusCode)
assert.Contains(t, actual, "provided credentials are invalid")
})

t.Run("case=should fail with correct CSRF error cause/type=api", func(t *testing.T) {
for k, tc := range []struct {
mod func(http.Header)
exp string
}{
{
mod: func(h http.Header) {
h.Add("Cookie", "name=bar")
},
exp: "The HTTP Request Header included the \\\"Cookie\\\" key",
},
{
mod: func(h http.Header) {
h.Add("Origin", "www.bar.com")
},
exp: "The HTTP Request Header included the \\\"Origin\\\" key",
},
} {
t.Run(fmt.Sprintf("case=%d", k), func(t *testing.T) {
f := testhelpers.InitializeLoginFlowViaAPI(t, apiClient, publicTS, false)
c := testhelpers.GetLoginFlowMethodConfig(t, f.Payload, identity.CredentialsTypePassword.String())

req := testhelpers.NewRequest(t, true, "POST", pointerx.StringR(c.Action), bytes.NewBufferString(testhelpers.EncodeFormAsJSON(t, true, values)))
tc.mod(req.Header)

res, err := apiClient.Do(req)
require.NoError(t, err)
defer res.Body.Close()

actual := string(x.MustReadAll(res.Body))
assert.EqualValues(t, http.StatusBadRequest, res.StatusCode)
assert.Contains(t, actual, tc.exp)
})
}
})
})

var expectValidationError = func(t *testing.T, isAPI, forced bool, values func(url.Values)) string {
Expand Down

0 comments on commit dd9cab0

Please sign in to comment.