package main import ( "bytes" "encoding/json" "net/http" "net/http/httptest" "testing" "github.com/google/uuid" "github.com/stretchr/testify/assert" ) // TestScannerEndpoints tests ebook scanner operations func TestScannerEndpoints(t *testing.T) { t.Run("POST /api/scanner/scan - Scan without admin role", func(t *testing.T) { payload := map[string]interface{}{ "folder_paths": []string{"/path/to/ebooks"}, } jsonData, _ := json.Marshal(payload) req := httptest.NewRequest("POST", "/api/scanner/scan", bytes.NewBuffer(jsonData)) req.Header.Set("Content-Type", "application/json") req.Header.Set("Authorization", "Bearer user-token") req.Header.Set("X-User-Role", "user") rr := httptest.NewRecorder() handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { userRole := r.Header.Get("X-User-Role") if userRole != "admin" { w.WriteHeader(http.StatusForbidden) w.Write([]byte(`{"error":"admin access required"}`)) return } w.WriteHeader(http.StatusOK) }) handler.ServeHTTP(rr, req) assert.Equal(t, http.StatusForbidden, rr.Code) }) t.Run("POST /api/scanner/scan - Scan without folder paths", func(t *testing.T) { payload := map[string]interface{}{} jsonData, _ := json.Marshal(payload) req := httptest.NewRequest("POST", "/api/scanner/scan", bytes.NewBuffer(jsonData)) req.Header.Set("Content-Type", "application/json") req.Header.Set("Authorization", "Bearer admin-token") req.Header.Set("X-User-Role", "admin") rr := httptest.NewRecorder() handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { var req map[string]interface{} if err := json.NewDecoder(r.Body).Decode(&req); err != nil { w.WriteHeader(http.StatusBadRequest) w.Write([]byte(`{"error":"invalid request"}`)) return } if _, ok := req["folder_paths"]; !ok { w.WriteHeader(http.StatusBadRequest) w.Write([]byte(`{"error":"folder_paths required for scanning"}`)) return } w.WriteHeader(http.StatusOK) }) handler.ServeHTTP(rr, req) assert.Equal(t, http.StatusBadRequest, rr.Code) }) t.Run("POST /api/scanner/scan - Scan with invalid folder paths", func(t *testing.T) { payload := map[string]interface{}{ "folder_paths": []string{"/nonexistent/path"}, } jsonData, _ := json.Marshal(payload) req := httptest.NewRequest("POST", "/api/scanner/scan", bytes.NewBuffer(jsonData)) req.Header.Set("Content-Type", "application/json") req.Header.Set("Authorization", "Bearer admin-token") req.Header.Set("X-User-Role", "admin") rr := httptest.NewRecorder() handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { var req map[string]interface{} if err := json.NewDecoder(r.Body).Decode(&req); err != nil { w.WriteHeader(http.StatusBadRequest) w.Write([]byte(`{"error":"invalid request"}`)) return } folderPaths, ok := req["folder_paths"].([]interface{}) if !ok || len(folderPaths) == 0 { w.WriteHeader(http.StatusBadRequest) w.Write([]byte(`{"error":"invalid folder paths"}`)) return } w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(`{"error":"scan failed: path does not exist"}`)) }) handler.ServeHTTP(rr, req) assert.Equal(t, http.StatusInternalServerError, rr.Code) }) t.Run("POST /api/scanner/scan - Successful scan", func(t *testing.T) { payload := map[string]interface{}{ "folder_paths": []string{"/valid/path"}, } jsonData, _ := json.Marshal(payload) req := httptest.NewRequest("POST", "/api/scanner/scan", bytes.NewBuffer(jsonData)) req.Header.Set("Content-Type", "application/json") req.Header.Set("Authorization", "Bearer admin-token") req.Header.Set("X-User-Role", "admin") rr := httptest.NewRecorder() handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) w.Write([]byte(`{"message":"scan completed"}`)) }) handler.ServeHTTP(rr, req) assert.Equal(t, http.StatusOK, rr.Code) }) t.Run("POST /api/scanner/start - Start scanner without admin role", func(t *testing.T) { req := httptest.NewRequest("POST", "/api/scanner/start", nil) req.Header.Set("Authorization", "Bearer user-token") req.Header.Set("X-User-Role", "user") rr := httptest.NewRecorder() handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { userRole := r.Header.Get("X-User-Role") if userRole != "admin" { w.WriteHeader(http.StatusForbidden) w.Write([]byte(`{"error":"admin access required"}`)) return } w.WriteHeader(http.StatusOK) }) handler.ServeHTTP(rr, req) assert.Equal(t, http.StatusForbidden, rr.Code) }) t.Run("POST /api/scanner/start - Start scanner successfully", func(t *testing.T) { req := httptest.NewRequest("POST", "/api/scanner/start", nil) req.Header.Set("Authorization", "Bearer admin-token") req.Header.Set("X-User-Role", "admin") rr := httptest.NewRecorder() handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) w.Write([]byte(`{"message":"scanner started"}`)) }) handler.ServeHTTP(rr, req) assert.Equal(t, http.StatusOK, rr.Code) }) t.Run("POST /api/scanner/stop - Stop scanner without admin role", func(t *testing.T) { req := httptest.NewRequest("POST", "/api/scanner/stop", nil) req.Header.Set("Authorization", "Bearer user-token") req.Header.Set("X-User-Role", "user") rr := httptest.NewRecorder() handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { userRole := r.Header.Get("X-User-Role") if userRole != "admin" { w.WriteHeader(http.StatusForbidden) w.Write([]byte(`{"error":"admin access required"}`)) return } w.WriteHeader(http.StatusOK) }) handler.ServeHTTP(rr, req) assert.Equal(t, http.StatusForbidden, rr.Code) }) t.Run("POST /api/scanner/stop - Stop scanner successfully", func(t *testing.T) { req := httptest.NewRequest("POST", "/api/scanner/stop", nil) req.Header.Set("Authorization", "Bearer admin-token") req.Header.Set("X-User-Role", "admin") rr := httptest.NewRecorder() handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) w.Write([]byte(`{"message":"scanner stopped"}`)) }) handler.ServeHTTP(rr, req) assert.Equal(t, http.StatusOK, rr.Code) }) } // TestEdgeCases tests various edge cases and boundary conditions func TestEdgeCases(t *testing.T) { t.Run("Empty request body", func(t *testing.T) { req := httptest.NewRequest("POST", "/api/auth/login", bytes.NewBuffer([]byte(""))) req.Header.Set("Content-Type", "application/json") rr := httptest.NewRecorder() handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { var req map[string]interface{} if err := json.NewDecoder(r.Body).Decode(&req); err != nil { w.WriteHeader(http.StatusBadRequest) w.Write([]byte(`{"error":"invalid request"}`)) return } w.WriteHeader(http.StatusOK) }) handler.ServeHTTP(rr, req) assert.Equal(t, http.StatusBadRequest, rr.Code) }) t.Run("Malformed JSON", func(t *testing.T) { req := httptest.NewRequest("POST", "/api/auth/login", bytes.NewBuffer([]byte("{invalid json}"))) req.Header.Set("Content-Type", "application/json") rr := httptest.NewRecorder() handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { var req map[string]interface{} if err := json.NewDecoder(r.Body).Decode(&req); err != nil { w.WriteHeader(http.StatusBadRequest) w.Write([]byte(`{"error":"invalid request"}`)) return } w.WriteHeader(http.StatusOK) }) handler.ServeHTTP(rr, req) assert.Equal(t, http.StatusBadRequest, rr.Code) }) t.Run("Very large payload", func(t *testing.T) { largeString := string(make([]byte, 100000)) payload := map[string]interface{}{ "email": largeString + "@example.com", "username": "user", "password": "password123", } jsonData, _ := json.Marshal(payload) req := httptest.NewRequest("POST", "/api/auth/register", bytes.NewBuffer(jsonData)) req.Header.Set("Content-Type", "application/json") rr := httptest.NewRecorder() handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusBadRequest) w.Write([]byte(`{"error":"email too long"}`)) }) handler.ServeHTTP(rr, req) assert.Equal(t, http.StatusBadRequest, rr.Code) }) t.Run("SQL Injection attempt", func(t *testing.T) { payload := map[string]interface{}{ "email": "test@example.com'; DROP TABLE users; --", "username": "sqlinjection", "password": "password123", } jsonData, _ := json.Marshal(payload) req := httptest.NewRequest("POST", "/api/auth/register", bytes.NewBuffer(jsonData)) req.Header.Set("Content-Type", "application/json") rr := httptest.NewRecorder() handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { var req map[string]interface{} if err := json.NewDecoder(r.Body).Decode(&req); err != nil { w.WriteHeader(http.StatusBadRequest) w.Write([]byte(`{"error":"invalid request"}`)) return } email := req["email"].(string) if len(email) > 255 { w.WriteHeader(http.StatusBadRequest) w.Write([]byte(`{"error":"email too long"}`)) return } w.WriteHeader(http.StatusCreated) }) handler.ServeHTTP(rr, req) // Should either succeed (if sanitized) or fail with validation error assert.True(t, rr.Code == http.StatusCreated || rr.Code == http.StatusBadRequest) }) t.Run("XSS attempt in fields", func(t *testing.T) { payload := map[string]interface{}{ "email": "test@example.com", "username": "", "password": "password123", } jsonData, _ := json.Marshal(payload) req := httptest.NewRequest("POST", "/api/auth/register", bytes.NewBuffer(jsonData)) req.Header.Set("Content-Type", "application/json") rr := httptest.NewRecorder() handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { var req map[string]interface{} if err := json.NewDecoder(r.Body).Decode(&req); err != nil { w.WriteHeader(http.StatusBadRequest) w.Write([]byte(`{"error":"invalid request"}`)) return } username := req["username"].(string) if len(username) > 50 { w.WriteHeader(http.StatusBadRequest) w.Write([]byte(`{"error":"username too long"}`)) return } w.WriteHeader(http.StatusCreated) }) handler.ServeHTTP(rr, req) assert.Equal(t, http.StatusCreated, rr.Code) }) t.Run("Rate limiting simulation", func(t *testing.T) { requestCount := 0 handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { requestCount++ if requestCount > 10 { w.WriteHeader(http.StatusTooManyRequests) w.Write([]byte(`{"error":"too many requests"}`)) return } w.WriteHeader(http.StatusOK) }) for i := 0; i < 15; i++ { req := httptest.NewRequest("GET", "/api/libraries/types", nil) rr := httptest.NewRecorder() handler.ServeHTTP(rr, req) if i >= 10 { assert.Equal(t, http.StatusTooManyRequests, rr.Code) } else { assert.Equal(t, http.StatusOK, rr.Code) } } }) } // TestHTMXRequests tests HTMX-specific responses func TestHTMXRequests(t *testing.T) { t.Run("Registration with HTMX header", func(t *testing.T) { payload := map[string]interface{}{ "email": "htmx@example.com", "username": "htmxuser", "password": "password123", } jsonData, _ := json.Marshal(payload) req := httptest.NewRequest("POST", "/api/auth/register", bytes.NewBuffer(jsonData)) req.Header.Set("Content-Type", "application/json") req.Header.Set("HX-Request", "true") rr := httptest.NewRecorder() handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { isHTMX := r.Header.Get("HX-Request") == "true" w.WriteHeader(http.StatusCreated) if isHTMX { w.Write([]byte(`
Registration successful! Redirecting...
`)) } else { json.NewEncoder(w).Encode(map[string]interface{}{ "token": "fake-token", "user": map[string]interface{}{ "id": uuid.New().String(), "email": "htmx@example.com", "username": "htmxuser", }, }) } }) handler.ServeHTTP(rr, req) assert.Equal(t, http.StatusCreated, rr.Code) assert.Contains(t, rr.Body.String(), "