Files
Charon/backend/internal/api/handlers/import_handler_sanitize_test.go
GitHub Actions 63cebf07ab Refactor services and improve error handling
- Updated file permissions in certificate_service_test.go and log_service_test.go to use octal notation.
- Added a new doc.go file to document the services package.
- Enhanced error handling in docker_service.go, log_service.go, notification_service.go, proxyhost_service.go, remoteserver_service.go, update_service.go, and uptime_service.go by logging errors when closing resources.
- Improved log_service.go to simplify log file processing and deduplication.
- Introduced CRUD tests for notification templates in notification_service_template_test.go.
- Removed the obsolete python_compile_check.sh script.
- Updated notification_service.go to improve template management functions.
- Added tests for uptime service notifications in uptime_service_notification_test.go.
2025-12-08 05:55:17 +00:00

66 lines
2.0 KiB
Go

package handlers
import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"regexp"
"strings"
"testing"
"github.com/Wikid82/charon/backend/internal/api/middleware"
"github.com/Wikid82/charon/backend/internal/logger"
"github.com/gin-gonic/gin"
)
func TestImportUploadSanitizesFilename(t *testing.T) {
gin.SetMode(gin.TestMode)
tmpDir := t.TempDir()
// set up in-memory DB for handler
db := OpenTestDB(t)
// Create a fake caddy executable to avoid dependency on system binary
fakeCaddy := filepath.Join(tmpDir, "caddy")
os.WriteFile(fakeCaddy, []byte("#!/bin/sh\nexit 0"), 0o755)
svc := NewImportHandler(db, fakeCaddy, tmpDir, "")
router := gin.New()
router.Use(middleware.RequestID())
router.POST("/import/upload", svc.Upload)
buf := &bytes.Buffer{}
logger.Init(true, buf)
maliciousFilename := "../evil\nfile.caddy"
payload := map[string]interface{}{"filename": maliciousFilename, "content": "site { respond \"ok\" }"}
bodyBytes, _ := json.Marshal(payload)
req := httptest.NewRequest(http.MethodPost, "/import/upload", bytes.NewReader(bodyBytes))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
out := buf.String()
// Extract the logged filename from either text or JSON log format
textRegex := regexp.MustCompile(`filename=?"?([^"\s]*)"?`)
jsonRegex := regexp.MustCompile(`"filename":"([^"]*)"`)
var loggedFilename string
if m := textRegex.FindStringSubmatch(out); len(m) == 2 {
loggedFilename = m[1]
} else if m := jsonRegex.FindStringSubmatch(out); len(m) == 2 {
loggedFilename = m[1]
} else {
// if we can't extract a filename value, fail the test
t.Fatalf("could not extract filename from logs: %s", out)
}
if strings.Contains(loggedFilename, "\n") || strings.Contains(loggedFilename, "\r") {
t.Fatalf("log filename contained raw newline: %q", loggedFilename)
}
if strings.Contains(loggedFilename, "..") {
t.Fatalf("log filename contained path traversal: %q", loggedFilename)
}
}