diff options
| author | Adam Mathes <adam@adammathes.com> | 2026-02-14 11:09:39 -0800 |
|---|---|---|
| committer | Adam Mathes <adam@adammathes.com> | 2026-02-14 11:09:39 -0800 |
| commit | 4d55202300f9648bdcf9be14aeb2b8034ca37fc3 (patch) | |
| tree | c77f662cac74dc7b36a355ad78e85029b045049f | |
| parent | b47721a02d3fdfb1b6a565df29c85e7c51d8c490 (diff) | |
| download | neko-4d55202300f9648bdcf9be14aeb2b8034ca37fc3.tar.gz neko-4d55202300f9648bdcf9be14aeb2b8034ca37fc3.tar.bz2 neko-4d55202300f9648bdcf9be14aeb2b8034ca37fc3.zip | |
feat: fix authentication to handle no-password scenario\n\n- Updated Authenticated() to return true when no password is configured\n- Updated apiLoginHandler to succeed when no password is set\n- Added comprehensive backend tests for both password/no-password cases\n- Added E2E tests for authentication flows (password tests are skipped by default)\n- All tests pass for both authentication scenarios\n\nFixes issue where app would require login even when no password was configured.\nNow properly supports passwordless mode for local development.
| -rw-r--r-- | frontend/tests/auth.spec.ts | 166 | ||||
| -rw-r--r-- | web/auth_test.go | 174 | ||||
| -rw-r--r-- | web/web.go | 16 |
3 files changed, 356 insertions, 0 deletions
diff --git a/frontend/tests/auth.spec.ts b/frontend/tests/auth.spec.ts new file mode 100644 index 0000000..4161a83 --- /dev/null +++ b/frontend/tests/auth.spec.ts @@ -0,0 +1,166 @@ +import { test, expect } from '@playwright/test'; + +/** + * E2E tests for authentication flows. + * + * These tests verify login behavior both with and without a password configured. + * The current setup assumes no password (default for dev), so the password-required + * tests are marked as skip. To run those, start the backend with --password=testpass. + */ + +test.describe('Authentication - No Password Required', () => { + test('should allow direct access to dashboard without login', async ({ page }) => { + // When no password is configured, users should be able to access + // the dashboard directly without seeing the login page + await page.goto('/v2/'); + + // Should not redirect to login + await expect(page).toHaveURL(/.*\/v2\/?$/); + + // Should see the dashboard elements + await expect(page.locator('h1.logo')).toContainText('🐱'); + await expect(page.getByText('Logout')).toBeVisible(); + }); + + test('should allow login with empty password', async ({ page }) => { + // Visit login page + await page.goto('/v2/login'); + + // Submit with empty password + const passwordInput = page.getByLabel(/password/i); + await expect(passwordInput).toBeVisible(); + + // Leave password empty and submit + await page.click('button[type="submit"]'); + + // Should redirect to dashboard + await expect(page).toHaveURL(/.*\/v2\/?$/, { timeout: 5000 }); + await expect(page.locator('h1.logo')).toContainText('🐱'); + }); + + test('should report authenticated status via API when no password', async ({ request }) => { + // Check auth status + const response = await request.get('/api/auth'); + expect(response.ok()).toBeTruthy(); + + const data = await response.json(); + expect(data.authenticated).toBe(true); + }); +}); + +test.describe('Authentication - Password Required', () => { + // These tests require the backend to be started with a password + // Example: neko --password=testpass + // Skip by default since dev environment has no password + + test.skip('should redirect to login when accessing protected routes', async ({ page, context }) => { + // Clear any existing cookies + await context.clearCookies(); + + // Try to access dashboard + await page.goto('/v2/'); + + // Should redirect to login + await expect(page).toHaveURL(/.*\/login/, { timeout: 5000 }); + }); + + test.skip('should reject incorrect password', async ({ page }) => { + await page.goto('/v2/login'); + + // Enter wrong password + await page.fill('input[type="password"]', 'wrongpassword'); + await page.click('button[type="submit"]'); + + // Should show error message + await expect(page.getByText(/bad credentials|login failed/i)).toBeVisible({ timeout: 3000 }); + + // Should still be on login page + await expect(page).toHaveURL(/.*\/login/); + }); + + test.skip('should accept correct password and redirect to dashboard', async ({ page }) => { + await page.goto('/v2/login'); + + // Enter correct password (must match what the server was started with) + await page.fill('input[type="password"]', 'testpass'); + await page.click('button[type="submit"]'); + + // Should redirect to dashboard + await expect(page).toHaveURL(/.*\/v2\/?$/, { timeout: 5000 }); + await expect(page.locator('h1.logo')).toContainText('🐱'); + await expect(page.getByText('Logout')).toBeVisible(); + }); + + test.skip('should persist authentication across page reloads', async ({ page }) => { + // Login first + await page.goto('/v2/login'); + await page.fill('input[type="password"]', 'testpass'); + await page.click('button[type="submit"]'); + await expect(page).toHaveURL(/.*\/v2\/?$/); + + // Reload the page + await page.reload(); + + // Should still be authenticated (not redirected to login) + await expect(page).toHaveURL(/.*\/v2\/?$/); + await expect(page.locator('h1.logo')).toContainText('🐱'); + }); + + test.skip('should logout and redirect to login page', async ({ page }) => { + // Login first + await page.goto('/v2/login'); + await page.fill('input[type="password"]', 'testpass'); + await page.click('button[type="submit"]'); + await expect(page).toHaveURL(/.*\/v2\/?$/); + + // Click logout + await page.click('text=Logout'); + + // Should redirect to login + await expect(page).toHaveURL(/.*\/login/); + + // Try to access dashboard again - should redirect to login + await page.goto('/v2/'); + await expect(page).toHaveURL(/.*\/login/); + }); + + test.skip('should report unauthenticated status via API', async ({ request, context }) => { + // Clear cookies + await context.clearCookies(); + + // Check auth status + const response = await request.get('/api/auth'); + expect(response.ok()).toBeTruthy(); + + const data = await response.json(); + expect(data.authenticated).toBe(false); + }); +}); + +test.describe('Authentication - Complete Flow', () => { + test('should handle complete user flow without password', async ({ page }) => { + // 1. Access dashboard directly + await page.goto('/v2/'); + await expect(page.locator('h1.logo')).toContainText('🐱'); + + // 2. Navigate to settings + await page.click('text=Settings'); + await expect(page).toHaveURL(/.*\/settings/); + + // 3. Add a feed (this tests that API calls work when no password) + const feedUrl = 'http://example.com/rss.xml'; + await page.fill('input[type="url"]', feedUrl); + await page.click('text=Add Feed'); + + // Wait for success (feed should appear) + await expect(page.getByText(feedUrl)).toBeVisible({ timeout: 3000 }); + + // 4. Navigate back to main view + await page.goto('/v2/'); + await expect(page.locator('h1.logo')).toContainText('🐱'); + + // 5. Logout (should work even with no password) + await page.click('text=Logout'); + await expect(page).toHaveURL(/.*\/login/); + }); +}); diff --git a/web/auth_test.go b/web/auth_test.go new file mode 100644 index 0000000..6f319b9 --- /dev/null +++ b/web/auth_test.go @@ -0,0 +1,174 @@ +package web + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" + + "adammathes.com/neko/config" +) + +// TestAuthenticationNoPassword tests that when no password is configured, +// all routes should be accessible without authentication +func TestAuthenticationNoPassword(t *testing.T) { + // Save original password and restore after test + originalPassword := config.Config.DigestPassword + defer func() { + config.Config.DigestPassword = originalPassword + }() + + // Set empty password (no authentication required) + config.Config.DigestPassword = "" + + // Create a test handler that returns 200 OK + testHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusOK) + w.Write([]byte("success")) + }) + + // Wrap with AuthWrap + wrappedHandler := AuthWrap(testHandler) + + // Test without any auth cookie - should succeed + req := httptest.NewRequest("GET", "/test", nil) + rr := httptest.NewRecorder() + wrappedHandler.ServeHTTP(rr, req) + + if rr.Code != http.StatusOK { + t.Errorf("Expected 200 OK when no password is set, got %d", rr.Code) + } + + body := rr.Body.String() + if body != "success" { + t.Errorf("Expected 'success' response, got %s", body) + } +} + +// TestAuthenticationWithPassword tests that when a password is configured, +// routes require authentication +func TestAuthenticationWithPassword(t *testing.T) { + // Save original password and restore after test + originalPassword := config.Config.DigestPassword + defer func() { + config.Config.DigestPassword = originalPassword + }() + + // Set a password + config.Config.DigestPassword = "testpassword" + + // Create a test handler + testHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusOK) + w.Write([]byte("success")) + }) + + // Wrap with AuthWrap + wrappedHandler := AuthWrap(testHandler) + + // Test without auth cookie - should redirect to login + req := httptest.NewRequest("GET", "/test", nil) + rr := httptest.NewRecorder() + wrappedHandler.ServeHTTP(rr, req) + + if rr.Code != http.StatusTemporaryRedirect { + t.Errorf("Expected 307 redirect when not authenticated, got %d", rr.Code) + } + + location := rr.Header().Get("Location") + if location != "/login/" { + t.Errorf("Expected redirect to /login/, got %s", location) + } +} + +// TestAuthenticationWithValidCookie tests that a valid auth cookie allows access +func TestAuthenticationWithValidCookie(t *testing.T) { + // Save original password and restore after test + originalPassword := config.Config.DigestPassword + defer func() { + config.Config.DigestPassword = originalPassword + }() + + password := "testpassword" + config.Config.DigestPassword = password + + // First, login to get a valid cookie + loginReq := httptest.NewRequest("POST", "/login/", strings.NewReader("password="+password)) + loginReq.Header.Set("Content-Type", "application/x-www-form-urlencoded") + loginRR := httptest.NewRecorder() + loginHandler(loginRR, loginReq) + + // Extract the auth cookie + var authCookie *http.Cookie + for _, cookie := range loginRR.Result().Cookies() { + if cookie.Name == "auth" { + authCookie = cookie + break + } + } + + if authCookie == nil { + t.Fatal("Expected auth cookie after successful login") + } + + // Now test with the valid cookie + testHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusOK) + w.Write([]byte("success")) + }) + + wrappedHandler := AuthWrap(testHandler) + + req := httptest.NewRequest("GET", "/test", nil) + req.AddCookie(authCookie) + rr := httptest.NewRecorder() + wrappedHandler.ServeHTTP(rr, req) + + if rr.Code != http.StatusOK { + t.Errorf("Expected 200 OK with valid auth cookie, got %d", rr.Code) + } +} + +// TestApiLoginNoPassword tests that API login works when no password is set +func TestApiLoginNoPassword(t *testing.T) { + originalPassword := config.Config.DigestPassword + defer func() { + config.Config.DigestPassword = originalPassword + }() + + config.Config.DigestPassword = "" + + req := httptest.NewRequest("POST", "/api/login", strings.NewReader("password=")) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + rr := httptest.NewRecorder() + apiLoginHandler(rr, req) + + // Should succeed with any password (or empty) when no password is configured + if rr.Code != http.StatusOK { + t.Errorf("Expected 200 OK for API login with no password configured, got %d", rr.Code) + } +} + +// TestApiAuthStatusNoPassword tests auth status endpoint when no password is set +func TestApiAuthStatusNoPassword(t *testing.T) { + originalPassword := config.Config.DigestPassword + defer func() { + config.Config.DigestPassword = originalPassword + }() + + config.Config.DigestPassword = "" + + req := httptest.NewRequest("GET", "/api/auth", nil) + rr := httptest.NewRecorder() + apiAuthStatusHandler(rr, req) + + // Should return authenticated:true when no password is set + if rr.Code != http.StatusOK { + t.Errorf("Expected 200 OK for auth status with no password, got %d", rr.Code) + } + + body := rr.Body.String() + if !strings.Contains(body, `"authenticated":true`) { + t.Errorf("Expected authenticated:true in response, got: %s", body) + } +} @@ -133,6 +133,11 @@ func logoutHandler(w http.ResponseWriter, r *http.Request) { } func Authenticated(r *http.Request) bool { + // If no password is configured, authentication is not required + if config.Config.DigestPassword == "" { + return true + } + pc, err := r.Cookie("auth") if err != nil { return false @@ -179,6 +184,17 @@ func apiLoginHandler(w http.ResponseWriter, r *http.Request) { http.Error(w, "method not allowed", http.StatusMethodNotAllowed) return } + + // If no password is configured, authentication is not required + if config.Config.DigestPassword == "" { + // Still set a dummy auth cookie for consistency + c := http.Cookie{Name: AuthCookie, Value: "noauth", Path: "/", MaxAge: SecondsInAYear, HttpOnly: true} + http.SetCookie(w, &c) + w.Header().Set("Content-Type", "application/json") + fmt.Fprintf(w, `{"status":"ok"}`) + return + } + username := r.FormValue("username") password := r.FormValue("password") |
