package httpapi import ( "bytes" "context" "encoding/json" "io" "log/slog" "net/http" "net/http/cookiejar" "net/http/httptest" "os" "path/filepath" "strconv" "strings" "testing" "github.com/miaopanel/miaopanel/internal/config" "github.com/miaopanel/miaopanel/internal/files" "github.com/miaopanel/miaopanel/internal/security" "github.com/miaopanel/miaopanel/internal/site" "github.com/miaopanel/miaopanel/internal/store" "github.com/miaopanel/miaopanel/internal/system" "github.com/miaopanel/miaopanel/internal/waf" "github.com/miaopanel/miaopanel/internal/webserver" ) const ( testEntry = "sec-entry" testPassword = "Passw0rd!123" ) type harness struct { ts *httptest.Server cli *http.Client url string db *store.Store cfg *config.Config } func newHarness(t *testing.T) *harness { t.Helper() dir := t.TempDir() cfg := config.Default() cfg.PanelDir = dir cfg.DataDir = filepath.Join(dir, "data") cfg.WebRoot = filepath.Join(dir, "wwwroot") cfg.LogDir = filepath.Join(dir, "logs") cfg.Entry = testEntry cfg.Nginx = config.Nginx{VhostDir: filepath.Join(dir, "vhost"), CertDir: filepath.Join(dir, "cert")} if err := cfg.EnsureDirs(); err != nil { t.Fatal(err) } db, err := store.Open(filepath.Join(cfg.DataDir, "panel.db")) if err != nil { t.Fatal(err) } t.Cleanup(func() { db.Close() }) hash, err := security.HashPassword(testPassword) if err != nil { t.Fatal(err) } if _, err := db.CreateUser(t.Context(), "admin", hash, "admin"); err != nil { t.Fatal(err) } runner := system.NewRunner() ng := webserver.New(cfg, runner) sites := site.NewService(cfg, db, ng, runner) fileSvc, err := files.New(cfg.WebRoot) if err != nil { t.Fatal(err) } t.Cleanup(func() { fileSvc.Close() }) logger := testLogger() wafSvc := waf.New(db, cfg, ng, sites) if err := wafSvc.Init(context.Background()); err != nil { t.Fatal(err) } collector := waf.NewCollector(db, cfg, logger) api := New(Options{Config: cfg, Store: db, Sites: sites, Files: fileSvc, WAF: wafSvc, Collector: collector, Nginx: ng, Runner: runner, Logger: logger, Version: "test"}) ts := httptest.NewServer(api.Handler()) t.Cleanup(ts.Close) jar, _ := cookiejar.New(nil) return &harness{ ts: ts, cli: &http.Client{Jar: jar}, url: ts.URL, db: db, cfg: cfg, } } func (h *harness) do(t *testing.T, method, path string, body any, csrf string) (int, map[string]any) { t.Helper() var rdr io.Reader if body != nil { raw, err := json.Marshal(body) if err != nil { t.Fatal(err) } rdr = bytes.NewReader(raw) } req, err := http.NewRequest(method, h.url+"/"+testEntry+path, rdr) if err != nil { t.Fatal(err) } if body != nil { req.Header.Set("Content-Type", "application/json") } if csrf != "" { req.Header.Set("X-CSRF-Token", csrf) } req.Header.Set("Origin", h.url) resp, err := h.cli.Do(req) if err != nil { t.Fatal(err) } defer resp.Body.Close() var env map[string]any _ = json.NewDecoder(resp.Body).Decode(&env) return resp.StatusCode, env } func (h *harness) login(t *testing.T) string { t.Helper() code, env := h.do(t, http.MethodPost, "/api/v1/auth/login", map[string]string{"username": "admin", "password": testPassword}, "") if code != http.StatusOK { t.Fatalf("login status %d: %v", code, env) } data := env["data"].(map[string]any) csrf, _ := data["csrf"].(string) if csrf == "" { t.Fatal("csrf missing in login response") } return csrf } func TestEntryPathHidesPanel(t *testing.T) { h := newHarness(t) resp, err := http.Get(h.url + "/api/v1/health") if err != nil { t.Fatal(err) } defer resp.Body.Close() if resp.StatusCode != http.StatusNotFound { t.Fatalf("unprotected path returned %d", resp.StatusCode) } resp2, err := http.Get(h.url + "/" + testEntry + "/api/v1/health") if err != nil { t.Fatal(err) } defer resp2.Body.Close() if resp2.StatusCode != http.StatusOK { t.Fatalf("health returned %d", resp2.StatusCode) } } func TestLoginAndSession(t *testing.T) { h := newHarness(t) csrf := h.login(t) code, env := h.do(t, http.MethodGet, "/api/v1/auth/session", nil, "") if code != http.StatusOK { t.Fatalf("session status %d", code) } data := env["data"].(map[string]any) if data["entry"] != testEntry { t.Fatalf("entry = %v", data["entry"]) } if data["csrf"] != csrf { t.Fatal("csrf mismatch between login and session") } } func TestLoginRateLimit(t *testing.T) { h := newHarness(t) for i := 0; i < 5; i++ { code, _ := h.do(t, http.MethodPost, "/api/v1/auth/login", map[string]string{"username": "admin", "password": "wrong"}, "") if code != http.StatusUnauthorized { t.Fatalf("attempt %d: status %d", i, code) } } code, env := h.do(t, http.MethodPost, "/api/v1/auth/login", map[string]string{"username": "admin", "password": testPassword}, "") if code != http.StatusTooManyRequests { t.Fatalf("expected 429, got %d (%v)", code, env) } } func TestCSRFRequired(t *testing.T) { h := newHarness(t) h.login(t) code, _ := h.do(t, http.MethodPost, "/api/v1/sites", map[string]any{ "name": "blog", "kind": "static", "domains": []string{"example.com"}, }, "") if code != http.StatusForbidden { t.Fatalf("missing csrf accepted: %d", code) } code, _ = h.do(t, http.MethodPost, "/api/v1/sites", map[string]any{ "name": "blog", "kind": "static", "domains": []string{"example.com"}, }, "wrong-token") if code != http.StatusForbidden { t.Fatalf("wrong csrf accepted: %d", code) } } func TestSiteCRUD(t *testing.T) { h := newHarness(t) csrf := h.login(t) code, env := h.do(t, http.MethodPost, "/api/v1/sites", map[string]any{ "name": "blog", "kind": "static", "domains": []string{"example.com"}, "options": map[string]any{"security_headers": true, "waf": true}, }, csrf) if code != http.StatusOK { t.Fatalf("create status %d: %v", code, env) } created := env["data"].(map[string]any) id := int64(created["id"].(float64)) if created["kind"] != "static" { t.Fatalf("unexpected site: %v", created) } // Configuration must exist on disk and be free of template leftovers. conf := filepath.Join(h.cfg.Nginx.VhostDir, "blog.conf") if !fileExists(conf) { t.Fatal("vhost not written") } code, env = h.do(t, http.MethodGet, "/api/v1/sites", nil, "") if code != http.StatusOK { t.Fatalf("list status %d", code) } if n := len(env["data"].([]any)); n != 1 { t.Fatalf("want 1 site, got %d", n) } code, _ = h.do(t, http.MethodPost, "/api/v1/sites/"+itoa(id)+"/action", map[string]string{"action": "start"}, csrf) if code != http.StatusBadRequest { t.Fatalf("static site start should be 400, got %d", code) } // Duplicate domain must be rejected with 400. code, env = h.do(t, http.MethodPost, "/api/v1/sites", map[string]any{ "name": "dup", "kind": "static", "domains": []string{"example.com"}, }, csrf) if code != http.StatusBadRequest { t.Fatalf("duplicate domain accepted: %d %v", code, env) } code, _ = h.do(t, http.MethodDelete, "/api/v1/sites/"+itoa(id)+"?remove_files=1", nil, csrf) if code != http.StatusOK { t.Fatalf("delete status %d", code) } if fileExists(conf) { t.Fatal("vhost not removed") } code, _ = h.do(t, http.MethodGet, "/api/v1/sites/"+itoa(id), nil, "") if code != http.StatusNotFound { t.Fatalf("deleted site still visible: %d", code) } } func TestUpdateSiteOptions(t *testing.T) { h := newHarness(t) csrf := h.login(t) _, env := h.do(t, http.MethodPost, "/api/v1/sites", map[string]any{ "name": "app", "kind": "node", "domains": []string{"app.example.com"}, "start_cmd": "npm start", }, csrf) created := env["data"].(map[string]any) id := int64(created["id"].(float64)) if created["port"].(float64) < 8000 { t.Fatalf("port not allocated: %v", created["port"]) } code, env := h.do(t, http.MethodPut, "/api/v1/sites/"+itoa(id), map[string]any{ "name": "app", "kind": "node", "domains": []string{"app.example.com"}, "start_cmd": "npm start", "port": created["port"], "remark": "updated", "options": map[string]any{"security_headers": true, "conn_per_ip": 20, "anti_leech": true, "ip_mode": "allow", "ip_list": []string{"10.0.0.1"}}, }, csrf) if code != http.StatusOK { t.Fatalf("update status %d: %v", code, env) } updated := env["data"].(map[string]any) if updated["remark"] != "updated" { t.Fatalf("remark not updated: %v", updated) } code, env = h.do(t, http.MethodGet, "/api/v1/sites/"+itoa(id)+"/config", nil, "") if code != http.StatusOK { t.Fatalf("config status %d", code) } files := env["data"].(map[string]any)["files"].(map[string]any) var found bool for path, content := range files { if strings.HasSuffix(path, "50-ip.conf") && strings.Contains(content.(string), "allow 10.0.0.1;") { found = true } } if !found { t.Fatalf("ip fragment not rendered: %v", files) } } func itoa(v int64) string { return strconv.FormatInt(v, 10) } func testLogger() *slog.Logger { return slog.New(slog.NewTextHandler(io.Discard, nil)) } func fileExists(p string) bool { _, err := os.Stat(p) return err == nil }