feat(security): #286 fix test
All checks were successful
Build Docker Image / Build-Docker-Image (push) Successful in 51s

This commit is contained in:
2024-12-08 23:21:29 +01:00
parent c9e0188b60
commit 9e060b6f12
8 changed files with 81 additions and 717 deletions

View File

@@ -14,6 +14,8 @@ import (
"time"
"github.com/google/uuid"
"github.com/stretchr/testify/assert"
"golang.org/x/net/html"
)
func TestHandleSignIn(t *testing.T) {
@@ -39,25 +41,35 @@ func TestHandleSignIn(t *testing.T) {
t.Fatalf("Error inserting user: %v", err)
}
formData := url.Values{
"email": {"mail@mail.de"},
"password": {"password"},
}
req, err := http.NewRequestWithContext(ctx, "POST", "http://localhost:8080/api/auth/signin", strings.NewReader(formData.Encode()))
if err != nil {
t.Fatalf("Error creating request: %v", err)
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req, err := http.NewRequestWithContext(ctx, "GET", "http://localhost:8080/auth/signin", nil)
assert.Nil(t, err)
resp, err := httpClient.Do(req)
if err != nil {
t.Fatalf("Error making request: %v", err)
assert.Nil(t, err)
html, err := html.Parse(resp.Body)
assert.Nil(t, err)
csrfToken := findCsrfToken(html)
assert.NotEqual(t, "", csrfToken)
anonymousSession := findCookie(resp, "id")
assert.NotNil(t, anonymousSession)
formData := url.Values{
"email": {"mail@mail.de"},
"password": {"password"},
"csrf-token": {csrfToken},
}
if resp.StatusCode != http.StatusSeeOther {
t.Fatalf("Expected status code 303, got %d", resp.StatusCode)
}
req, err = http.NewRequestWithContext(ctx, "POST", "http://localhost:8080/api/auth/signin", strings.NewReader(formData.Encode()))
assert.Nil(t, err)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Cookie", anonymousSession.Name+"="+anonymousSession.Value)
resp, err = httpClient.Do(req)
assert.Nil(t, err)
assert.Equal(t, http.StatusSeeOther, resp.StatusCode)
cookie := findCookie(resp, "id")
if cookie == nil {
@@ -165,3 +177,44 @@ func waitForReady(
}
}
}
func findCsrfToken(data *html.Node) string {
attr := getTokenAttribute(data)
if attr != nil {
return attr.Val
}
if data.FirstChild != nil {
if token := findCsrfToken(data.FirstChild); token != "" {
return token
}
}
if data.NextSibling != nil {
if token := findCsrfToken(data.NextSibling); token != "" {
return token
}
}
return ""
}
func getTokenAttribute(data *html.Node) *html.Attribute {
returnValue := false
for _, attr := range data.Attr {
if attr.Key == "name" && attr.Val == "csrf-token" {
returnValue = true
}
}
if !returnValue {
return nil
}
for _, attr := range data.Attr {
if attr.Key == "value" {
return &attr
}
}
return nil
}