Skip to content
Open
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
10 changes: 9 additions & 1 deletion backend/middleware/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ type credentialsPayload struct {
}

// AuthMiddleware validates that the user is authenticated and injects session
// credentials into the request body. This ensures:
// credentials into the X-User-* request headers and, for POST requests, the
// JSON request body. This ensures:
// 1. Only authenticated users can access protected endpoints
// 2. Users cannot manipulate credentials to access other users' data
// 3. Frontend doesn't need to store/send sensitive encryption secrets
Expand Down Expand Up @@ -51,6 +52,13 @@ func AuthMiddleware(store *sessions.CookieStore) func(http.Handler) http.Handler
return
}

// GET /tasks reads credentials from the X-User-* headers, so overwrite
// them with the session values too. Otherwise a client could send
// another user's credentials and have them used.
r.Header.Set("X-User-Email", sessionEmail)
r.Header.Set("X-User-UUID", sessionUUID)
r.Header.Set("X-Encryption-Secret", sessionSecret)

// For POST requests with JSON body, inject session credentials
if r.Method == http.MethodPost && r.Body != nil {
// Read the body
Expand Down
126 changes: 126 additions & 0 deletions backend/middleware/auth_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
package middleware

import (
"encoding/gob"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"

"github.com/gorilla/sessions"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func init() {
gob.Register(map[string]interface{}{})
}

func newTestStore() *sessions.CookieStore {
return sessions.NewCookieStore([]byte("test-session-key-0123456789abcdef"))
}

// sessionCookie returns a cookie for a session logged in as the given user.
func sessionCookie(t *testing.T, store *sessions.CookieStore, email, uuid, secret string) *http.Cookie {
t.Helper()
req := httptest.NewRequest(http.MethodGet, "/", nil)
rr := httptest.NewRecorder()
session, err := store.Get(req, "session-name")
require.NoError(t, err)
session.Values["user"] = map[string]interface{}{
"email": email,
"uuid": uuid,
"encryption_secret": secret,
}
require.NoError(t, session.Save(req, rr))
cookies := rr.Result().Cookies()
require.NotEmpty(t, cookies)
return cookies[0]
}

func TestAuthMiddleware_GetUsesSessionCredentialsNotClientHeaders(t *testing.T) {
store := newTestStore()
var gotEmail, gotUUID, gotSecret string
handler := AuthMiddleware(store)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotEmail = r.Header.Get("X-User-Email")
gotUUID = r.Header.Get("X-User-UUID")
gotSecret = r.Header.Get("X-Encryption-Secret")
}))

// Logged in as user A, but sending user B's credentials in the headers.
req := httptest.NewRequest(http.MethodGet, "/tasks", nil)
req.AddCookie(sessionCookie(t, store, "a@example.com", "uuid-a", "secret-a"))
req.Header.Set("X-User-Email", "b@example.com")
req.Header.Set("X-User-UUID", "uuid-b")
req.Header.Set("X-Encryption-Secret", "secret-b")
rr := httptest.NewRecorder()
handler.ServeHTTP(rr, req)

assert.Equal(t, http.StatusOK, rr.Code)
assert.Equal(t, "a@example.com", gotEmail)
assert.Equal(t, "uuid-a", gotUUID)
assert.Equal(t, "secret-a", gotSecret)
}

func TestAuthMiddleware_GetWithoutHeadersGetsSessionCredentials(t *testing.T) {
store := newTestStore()
var gotEmail, gotUUID, gotSecret string
handler := AuthMiddleware(store)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotEmail = r.Header.Get("X-User-Email")
gotUUID = r.Header.Get("X-User-UUID")
gotSecret = r.Header.Get("X-Encryption-Secret")
}))

req := httptest.NewRequest(http.MethodGet, "/tasks", nil)
req.AddCookie(sessionCookie(t, store, "a@example.com", "uuid-a", "secret-a"))
rr := httptest.NewRecorder()
handler.ServeHTTP(rr, req)

assert.Equal(t, http.StatusOK, rr.Code)
assert.Equal(t, "a@example.com", gotEmail)
assert.Equal(t, "uuid-a", gotUUID)
assert.Equal(t, "secret-a", gotSecret)
}

func TestAuthMiddleware_PostBodyCredentialsOverwrittenFromSession(t *testing.T) {
store := newTestStore()
var body map[string]interface{}
handler := AuthMiddleware(store)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
raw, err := io.ReadAll(r.Body)
require.NoError(t, err)
require.NoError(t, json.Unmarshal(raw, &body))
}))

req := httptest.NewRequest(http.MethodPost, "/add-task", strings.NewReader(
`{"email":"b@example.com","UUID":"uuid-b","encryptionSecret":"secret-b","description":"x"}`,
))
req.AddCookie(sessionCookie(t, store, "a@example.com", "uuid-a", "secret-a"))
rr := httptest.NewRecorder()
handler.ServeHTTP(rr, req)

assert.Equal(t, http.StatusOK, rr.Code)
assert.Equal(t, "a@example.com", body["email"])
assert.Equal(t, "uuid-a", body["UUID"])
assert.Equal(t, "secret-a", body["encryptionSecret"])
assert.Equal(t, "x", body["description"])
}

func TestAuthMiddleware_RejectsRequestWithoutSession(t *testing.T) {
store := newTestStore()
called := false
handler := AuthMiddleware(store)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
called = true
}))

req := httptest.NewRequest(http.MethodGet, "/tasks", nil)
req.Header.Set("X-User-Email", "b@example.com")
req.Header.Set("X-User-UUID", "uuid-b")
req.Header.Set("X-Encryption-Secret", "secret-b")
rr := httptest.NewRecorder()
handler.ServeHTTP(rr, req)

assert.Equal(t, http.StatusUnauthorized, rr.Code)
assert.False(t, called)
}