whoami_session_test.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package api
  2. import (
  3. "context"
  4. "io"
  5. "net/http"
  6. "strings"
  7. "testing"
  8. "connectrpc.com/connect"
  9. "github.com/stretchr/testify/assert"
  10. "github.com/stretchr/testify/require"
  11. apiv1 "github.com/OliveTin/OliveTin/gen/olivetin/api/v1"
  12. apiv1connect "github.com/OliveTin/OliveTin/gen/olivetin/api/v1/apiv1connect"
  13. config "github.com/OliveTin/OliveTin/internal/config"
  14. )
  15. func loginLocalUserForSessionCookie(t *testing.T, client apiv1connect.OliveTinApiServiceClient) *http.Cookie {
  16. t.Helper()
  17. resp, err := client.LocalUserLogin(context.Background(), connect.NewRequest(&apiv1.LocalUserLoginRequest{
  18. Username: "alice",
  19. Password: "correct horse",
  20. }))
  21. require.NoError(t, err)
  22. require.True(t, resp.Msg.GetSuccess())
  23. header := http.Header{"Set-Cookie": resp.Header().Values("Set-Cookie")}
  24. for _, cookie := range (&http.Response{Header: header}).Cookies() {
  25. if cookie.Name == "olivetin-sid-local" && cookie.Value != "" {
  26. return cookie
  27. }
  28. }
  29. t.Fatal("login did not set the olivetin-sid-local cookie")
  30. return nil
  31. }
  32. func postWhoAmI(t *testing.T, baseURL string, cookie *http.Cookie) string {
  33. t.Helper()
  34. req, err := http.NewRequestWithContext(t.Context(), http.MethodPost, baseURL+"/api/WhoAmI", strings.NewReader("{}"))
  35. require.NoError(t, err)
  36. req.Header.Set("Content-Type", "application/json")
  37. req.AddCookie(cookie)
  38. resp, err := http.DefaultClient.Do(req)
  39. require.NoError(t, err)
  40. defer func() { assert.NoError(t, resp.Body.Close()) }()
  41. body, err := io.ReadAll(resp.Body)
  42. require.NoError(t, err)
  43. require.Equal(t, http.StatusOK, resp.StatusCode, string(body))
  44. return string(body)
  45. }
  46. func TestWhoAmINeverReturnsSessionID(t *testing.T) {
  47. hash, err := createHash("correct horse")
  48. require.NoError(t, err)
  49. cfg := config.DefaultConfig()
  50. cfg.SetDir(t.TempDir())
  51. cfg.AuthLocalUsers.Enabled = true
  52. cfg.AuthLocalUsers.Users = []*config.LocalUser{{Username: "alice", Password: hash}}
  53. ts, client := getNewTestServerAndClient(cfg)
  54. defer ts.Close()
  55. cookie := loginLocalUserForSessionCookie(t, client)
  56. body := postWhoAmI(t, ts.URL, cookie)
  57. assert.Contains(t, body, `"authenticatedUser":"alice"`)
  58. assert.NotContains(t, body, cookie.Value, "WhoAmI must not return the session cookie value")
  59. assert.NotContains(t, body, `"sid"`)
  60. assert.Contains(t, body, `"sessionFingerprint":"`)
  61. }