Files
Charon/backend/internal/api/handlers/logs_handler_coverage_test.go
akanealw eec8c28fb3
Some checks failed
Go Benchmark / Performance Regression Check (push) Has been cancelled
Cerberus Integration / Cerberus Security Stack Integration (push) Has been cancelled
Upload Coverage to Codecov / Backend Codecov Upload (push) Has been cancelled
Upload Coverage to Codecov / Frontend Codecov Upload (push) Has been cancelled
CodeQL - Analyze / CodeQL analysis (go) (push) Has been cancelled
CodeQL - Analyze / CodeQL analysis (javascript-typescript) (push) Has been cancelled
CrowdSec Integration / CrowdSec Bouncer Integration (push) Has been cancelled
Docker Build, Publish & Test / build-and-push (push) Has been cancelled
Quality Checks / Auth Route Protection Contract (push) Has been cancelled
Quality Checks / Codecov Trigger/Comment Parity Guard (push) Has been cancelled
Quality Checks / Backend (Go) (push) Has been cancelled
Quality Checks / Frontend (React) (push) Has been cancelled
Rate Limit integration / Rate Limiting Integration (push) Has been cancelled
Security Scan (PR) / Trivy Binary Scan (push) Has been cancelled
Supply Chain Verification (PR) / Verify Supply Chain (push) Has been cancelled
WAF integration / Coraza WAF Integration (push) Has been cancelled
Docker Build, Publish & Test / Security Scan PR Image (push) Has been cancelled
Repo Health Check / Repo health (push) Has been cancelled
History Rewrite Dry-Run / Dry-run preview for history rewrite (push) Has been cancelled
Prune Renovate Branches / prune (push) Has been cancelled
Renovate / renovate (push) Has been cancelled
Nightly Build & Package / sync-development-to-nightly (push) Has been cancelled
Nightly Build & Package / Trigger Nightly Validation Workflows (push) Has been cancelled
Nightly Build & Package / build-and-push-nightly (push) Has been cancelled
Nightly Build & Package / test-nightly-image (push) Has been cancelled
Nightly Build & Package / verify-nightly-supply-chain (push) Has been cancelled
Update GeoLite2 Checksum / update-checksum (push) Has been cancelled
Container Registry Prune / prune-ghcr (push) Has been cancelled
Container Registry Prune / prune-dockerhub (push) Has been cancelled
Container Registry Prune / summarize (push) Has been cancelled
Supply Chain Verification / Verify SBOM (push) Has been cancelled
Supply Chain Verification / Verify Release Artifacts (push) Has been cancelled
Supply Chain Verification / Verify Docker Image Supply Chain (push) Has been cancelled
Monitor Caddy Major Release / check-caddy-major (push) Has been cancelled
Weekly Nightly to Main Promotion / Verify Nightly Branch Health (push) Has been cancelled
Weekly Nightly to Main Promotion / Create Promotion PR (push) Has been cancelled
Weekly Nightly to Main Promotion / Trigger Missing Required Checks (push) Has been cancelled
Weekly Nightly to Main Promotion / Notify on Failure (push) Has been cancelled
Weekly Nightly to Main Promotion / Workflow Summary (push) Has been cancelled
Weekly Security Rebuild / Security Rebuild & Scan (push) Has been cancelled
changed perms
2026-04-22 18:19:14 +00:00

225 lines
7.2 KiB
Go
Executable File

package handlers
import (
"fmt"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"testing"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/Wikid82/charon/backend/internal/config"
"github.com/Wikid82/charon/backend/internal/services"
)
func TestLogsHandler_Read_FilterBySearch(t *testing.T) {
tmpDir := t.TempDir()
dataDir := filepath.Join(tmpDir, "data")
_ = os.MkdirAll(dataDir, 0o750) // #nosec G301 -- test directory
dbPath := filepath.Join(dataDir, "charon.db")
logsDir := filepath.Join(dataDir, "logs")
_ = os.MkdirAll(logsDir, 0o750) // #nosec G301 -- test directory
// Write JSON log lines
content := `{"level":"info","ts":1600000000,"msg":"request handled","request":{"method":"GET","host":"example.com","uri":"/api/search","remote_ip":"1.2.3.4"},"status":200}
{"level":"error","ts":1600000060,"msg":"error occurred","request":{"method":"POST","host":"example.com","uri":"/api/submit","remote_ip":"5.6.7.8"},"status":500}
`
_ = os.WriteFile(filepath.Join(logsDir, "access.log"), []byte(content), 0o600) // #nosec G306 -- test fixture
cfg := &config.Config{DatabasePath: dbPath}
svc := services.NewLogService(cfg)
h := NewLogsHandler(svc)
// Test with search filter
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Params = gin.Params{{Key: "filename", Value: "access.log"}}
c.Request = httptest.NewRequest("GET", "/logs/access.log?search=error", http.NoBody)
h.Read(c)
assert.Equal(t, 200, w.Code)
assert.Contains(t, w.Body.String(), "error")
}
func TestLogsHandler_Read_FilterByHost(t *testing.T) {
tmpDir := t.TempDir()
dataDir := filepath.Join(tmpDir, "data")
_ = os.MkdirAll(dataDir, 0o750) // #nosec G301 -- test directory
dbPath := filepath.Join(dataDir, "charon.db")
logsDir := filepath.Join(dataDir, "logs")
_ = os.MkdirAll(logsDir, 0o750) // #nosec G301 -- test directory
content := `{"level":"info","ts":1600000000,"msg":"request handled","request":{"method":"GET","host":"example.com","uri":"/","remote_ip":"1.2.3.4"},"status":200}
{"level":"info","ts":1600000001,"msg":"request handled","request":{"method":"GET","host":"other.com","uri":"/","remote_ip":"1.2.3.4"},"status":200}
`
_ = os.WriteFile(filepath.Join(logsDir, "access.log"), []byte(content), 0o600) // #nosec G306 -- test fixture
cfg := &config.Config{DatabasePath: dbPath}
svc := services.NewLogService(cfg)
h := NewLogsHandler(svc)
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Params = gin.Params{{Key: "filename", Value: "access.log"}}
c.Request = httptest.NewRequest("GET", "/logs/access.log?host=example.com", http.NoBody)
h.Read(c)
assert.Equal(t, 200, w.Code)
}
func TestLogsHandler_Read_FilterByLevel(t *testing.T) {
tmpDir := t.TempDir()
dataDir := filepath.Join(tmpDir, "data")
_ = os.MkdirAll(dataDir, 0o750) // #nosec G301 -- test directory
dbPath := filepath.Join(dataDir, "charon.db")
logsDir := filepath.Join(dataDir, "logs")
_ = os.MkdirAll(logsDir, 0o750) // #nosec G301 -- test directory
content := `{"level":"info","ts":1600000000,"msg":"info message"}
{"level":"error","ts":1600000001,"msg":"error message"}
`
_ = os.WriteFile(filepath.Join(logsDir, "access.log"), []byte(content), 0o600) // #nosec G306 -- test fixture
cfg := &config.Config{DatabasePath: dbPath}
svc := services.NewLogService(cfg)
h := NewLogsHandler(svc)
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Params = gin.Params{{Key: "filename", Value: "access.log"}}
c.Request = httptest.NewRequest("GET", "/logs/access.log?level=error", http.NoBody)
h.Read(c)
assert.Equal(t, 200, w.Code)
}
func TestLogsHandler_Read_FilterByStatus(t *testing.T) {
tmpDir := t.TempDir()
dataDir := filepath.Join(tmpDir, "data")
_ = os.MkdirAll(dataDir, 0o750) // #nosec G301 -- test directory
dbPath := filepath.Join(dataDir, "charon.db")
logsDir := filepath.Join(dataDir, "logs")
_ = os.MkdirAll(logsDir, 0o750) // #nosec G301 -- test directory
content := `{"level":"info","ts":1600000000,"msg":"200 OK","request":{"host":"example.com"},"status":200}
{"level":"error","ts":1600000001,"msg":"500 Error","request":{"host":"example.com"},"status":500}
`
_ = os.WriteFile(filepath.Join(logsDir, "access.log"), []byte(content), 0o600) // #nosec G306 -- test fixture
cfg := &config.Config{DatabasePath: dbPath}
svc := services.NewLogService(cfg)
h := NewLogsHandler(svc)
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Params = gin.Params{{Key: "filename", Value: "access.log"}}
c.Request = httptest.NewRequest("GET", "/logs/access.log?status=500", http.NoBody)
h.Read(c)
assert.Equal(t, 200, w.Code)
}
func TestLogsHandler_Read_SortAsc(t *testing.T) {
tmpDir := t.TempDir()
dataDir := filepath.Join(tmpDir, "data")
_ = os.MkdirAll(dataDir, 0o750) // #nosec G301 -- test directory
dbPath := filepath.Join(dataDir, "charon.db")
logsDir := filepath.Join(dataDir, "logs")
_ = os.MkdirAll(logsDir, 0o750) // #nosec G301 -- test directory
content := `{"level":"info","ts":1600000000,"msg":"first"}
{"level":"info","ts":1600000001,"msg":"second"}
`
_ = os.WriteFile(filepath.Join(logsDir, "access.log"), []byte(content), 0o600) // #nosec G306 -- test fixture
cfg := &config.Config{DatabasePath: dbPath}
svc := services.NewLogService(cfg)
h := NewLogsHandler(svc)
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Params = gin.Params{{Key: "filename", Value: "access.log"}}
c.Request = httptest.NewRequest("GET", "/logs/access.log?sort=asc", http.NoBody)
h.Read(c)
assert.Equal(t, 200, w.Code)
}
func TestLogsHandler_List_DirectoryIsFile(t *testing.T) {
tmpDir := t.TempDir()
dataDir := filepath.Join(tmpDir, "data")
_ = os.MkdirAll(dataDir, 0o750) // #nosec G301 -- test directory
dbPath := filepath.Join(dataDir, "charon.db")
logsDir := filepath.Join(dataDir, "logs")
// Create logs dir as a file to cause error
_ = os.WriteFile(logsDir, []byte("not a dir"), 0o600) // #nosec G306 -- test fixture
cfg := &config.Config{DatabasePath: dbPath}
svc := services.NewLogService(cfg)
h := NewLogsHandler(svc)
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest("GET", "/logs", http.NoBody)
h.List(c)
// Service may handle this gracefully or error
assert.Contains(t, []int{200, 500}, w.Code)
}
func TestLogsHandler_Download_TempFileError(t *testing.T) {
tmpDir := t.TempDir()
dataDir := filepath.Join(tmpDir, "data")
logsDir := filepath.Join(dataDir, "logs")
require.NoError(t, os.MkdirAll(logsDir, 0o750)) // #nosec G301 -- test directory
dbPath := filepath.Join(dataDir, "charon.db")
logPath := filepath.Join(logsDir, "access.log")
require.NoError(t, os.WriteFile(logPath, []byte("log line"), 0o600)) // #nosec G306 -- test fixture
cfg := &config.Config{DatabasePath: dbPath}
svc := services.NewLogService(cfg)
h := NewLogsHandler(svc)
originalCreateTemp := createTempFile
createTempFile = func(dir, pattern string) (*os.File, error) {
return nil, fmt.Errorf("boom")
}
t.Cleanup(func() {
createTempFile = originalCreateTemp
})
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Params = gin.Params{{Key: "filename", Value: "access.log"}}
c.Request = httptest.NewRequest("GET", "/logs/access.log", http.NoBody)
h.Download(c)
assert.Equal(t, http.StatusInternalServerError, w.Code)
}