仰望星辰工作室

miaopanel

miaopanel/ internal/httpapi/api_test.go 8.8 KB · 319 行 原始文件
1package httpapi
2
3import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "io"
8 "log/slog"
9 "net/http"
10 "net/http/cookiejar"
11 "net/http/httptest"
12 "os"
13 "path/filepath"
14 "strconv"
15 "strings"
16 "testing"
17
18 "github.com/miaopanel/miaopanel/internal/config"
19 "github.com/miaopanel/miaopanel/internal/files"
20 "github.com/miaopanel/miaopanel/internal/security"
21 "github.com/miaopanel/miaopanel/internal/site"
22 "github.com/miaopanel/miaopanel/internal/store"
23 "github.com/miaopanel/miaopanel/internal/system"
24 "github.com/miaopanel/miaopanel/internal/waf"
25 "github.com/miaopanel/miaopanel/internal/webserver"
26)
27
28const (
29 testEntry = "sec-entry"
30 testPassword = "Passw0rd!123"
31)
32
33type harness struct {
34 ts *httptest.Server
35 cli *http.Client
36 url string
37 db *store.Store
38 cfg *config.Config
39}
40
41func newHarness(t *testing.T) *harness {
42 t.Helper()
43 dir := t.TempDir()
44 cfg := config.Default()
45 cfg.PanelDir = dir
46 cfg.DataDir = filepath.Join(dir, "data")
47 cfg.WebRoot = filepath.Join(dir, "wwwroot")
48 cfg.LogDir = filepath.Join(dir, "logs")
49 cfg.Entry = testEntry
50 cfg.Nginx = config.Nginx{VhostDir: filepath.Join(dir, "vhost"), CertDir: filepath.Join(dir, "cert")}
51 if err := cfg.EnsureDirs(); err != nil {
52 t.Fatal(err)
53 }
54 db, err := store.Open(filepath.Join(cfg.DataDir, "panel.db"))
55 if err != nil {
56 t.Fatal(err)
57 }
58 t.Cleanup(func() { db.Close() })
59 hash, err := security.HashPassword(testPassword)
60 if err != nil {
61 t.Fatal(err)
62 }
63 if _, err := db.CreateUser(t.Context(), "admin", hash, "admin"); err != nil {
64 t.Fatal(err)
65 }
66 runner := system.NewRunner()
67 ng := webserver.New(cfg, runner)
68 sites := site.NewService(cfg, db, ng, runner)
69 fileSvc, err := files.New(cfg.WebRoot)
70 if err != nil {
71 t.Fatal(err)
72 }
73 t.Cleanup(func() { fileSvc.Close() })
74 logger := testLogger()
75 wafSvc := waf.New(db, cfg, ng, sites)
76 if err := wafSvc.Init(context.Background()); err != nil {
77 t.Fatal(err)
78 }
79 collector := waf.NewCollector(db, cfg, logger)
80 api := New(Options{Config: cfg, Store: db, Sites: sites, Files: fileSvc,
81 WAF: wafSvc, Collector: collector, Nginx: ng,
82 Runner: runner, Logger: logger, Version: "test"})
83 ts := httptest.NewServer(api.Handler())
84 t.Cleanup(ts.Close)
85 jar, _ := cookiejar.New(nil)
86 return &harness{
87 ts: ts,
88 cli: &http.Client{Jar: jar},
89 url: ts.URL,
90 db: db,
91 cfg: cfg,
92 }
93}
94
95func (h *harness) do(t *testing.T, method, path string, body any, csrf string) (int, map[string]any) {
96 t.Helper()
97 var rdr io.Reader
98 if body != nil {
99 raw, err := json.Marshal(body)
100 if err != nil {
101 t.Fatal(err)
102 }
103 rdr = bytes.NewReader(raw)
104 }
105 req, err := http.NewRequest(method, h.url+"/"+testEntry+path, rdr)
106 if err != nil {
107 t.Fatal(err)
108 }
109 if body != nil {
110 req.Header.Set("Content-Type", "application/json")
111 }
112 if csrf != "" {
113 req.Header.Set("X-CSRF-Token", csrf)
114 }
115 req.Header.Set("Origin", h.url)
116 resp, err := h.cli.Do(req)
117 if err != nil {
118 t.Fatal(err)
119 }
120 defer resp.Body.Close()
121 var env map[string]any
122 _ = json.NewDecoder(resp.Body).Decode(&env)
123 return resp.StatusCode, env
124}
125
126func (h *harness) login(t *testing.T) string {
127 t.Helper()
128 code, env := h.do(t, http.MethodPost, "/api/v1/auth/login",
129 map[string]string{"username": "admin", "password": testPassword}, "")
130 if code != http.StatusOK {
131 t.Fatalf("login status %d: %v", code, env)
132 }
133 data := env["data"].(map[string]any)
134 csrf, _ := data["csrf"].(string)
135 if csrf == "" {
136 t.Fatal("csrf missing in login response")
137 }
138 return csrf
139}
140
141func TestEntryPathHidesPanel(t *testing.T) {
142 h := newHarness(t)
143 resp, err := http.Get(h.url + "/api/v1/health")
144 if err != nil {
145 t.Fatal(err)
146 }
147 defer resp.Body.Close()
148 if resp.StatusCode != http.StatusNotFound {
149 t.Fatalf("unprotected path returned %d", resp.StatusCode)
150 }
151 resp2, err := http.Get(h.url + "/" + testEntry + "/api/v1/health")
152 if err != nil {
153 t.Fatal(err)
154 }
155 defer resp2.Body.Close()
156 if resp2.StatusCode != http.StatusOK {
157 t.Fatalf("health returned %d", resp2.StatusCode)
158 }
159}
160
161func TestLoginAndSession(t *testing.T) {
162 h := newHarness(t)
163 csrf := h.login(t)
164 code, env := h.do(t, http.MethodGet, "/api/v1/auth/session", nil, "")
165 if code != http.StatusOK {
166 t.Fatalf("session status %d", code)
167 }
168 data := env["data"].(map[string]any)
169 if data["entry"] != testEntry {
170 t.Fatalf("entry = %v", data["entry"])
171 }
172 if data["csrf"] != csrf {
173 t.Fatal("csrf mismatch between login and session")
174 }
175}
176
177func TestLoginRateLimit(t *testing.T) {
178 h := newHarness(t)
179 for i := 0; i < 5; i++ {
180 code, _ := h.do(t, http.MethodPost, "/api/v1/auth/login",
181 map[string]string{"username": "admin", "password": "wrong"}, "")
182 if code != http.StatusUnauthorized {
183 t.Fatalf("attempt %d: status %d", i, code)
184 }
185 }
186 code, env := h.do(t, http.MethodPost, "/api/v1/auth/login",
187 map[string]string{"username": "admin", "password": testPassword}, "")
188 if code != http.StatusTooManyRequests {
189 t.Fatalf("expected 429, got %d (%v)", code, env)
190 }
191}
192
193func TestCSRFRequired(t *testing.T) {
194 h := newHarness(t)
195 h.login(t)
196 code, _ := h.do(t, http.MethodPost, "/api/v1/sites", map[string]any{
197 "name": "blog", "kind": "static", "domains": []string{"example.com"},
198 }, "")
199 if code != http.StatusForbidden {
200 t.Fatalf("missing csrf accepted: %d", code)
201 }
202 code, _ = h.do(t, http.MethodPost, "/api/v1/sites", map[string]any{
203 "name": "blog", "kind": "static", "domains": []string{"example.com"},
204 }, "wrong-token")
205 if code != http.StatusForbidden {
206 t.Fatalf("wrong csrf accepted: %d", code)
207 }
208}
209
210func TestSiteCRUD(t *testing.T) {
211 h := newHarness(t)
212 csrf := h.login(t)
213
214 code, env := h.do(t, http.MethodPost, "/api/v1/sites", map[string]any{
215 "name": "blog", "kind": "static", "domains": []string{"example.com"},
216 "options": map[string]any{"security_headers": true, "waf": true},
217 }, csrf)
218 if code != http.StatusOK {
219 t.Fatalf("create status %d: %v", code, env)
220 }
221 created := env["data"].(map[string]any)
222 id := int64(created["id"].(float64))
223 if created["kind"] != "static" {
224 t.Fatalf("unexpected site: %v", created)
225 }
226
227 // Configuration must exist on disk and be free of template leftovers.
228 conf := filepath.Join(h.cfg.Nginx.VhostDir, "blog.conf")
229 if !fileExists(conf) {
230 t.Fatal("vhost not written")
231 }
232
233 code, env = h.do(t, http.MethodGet, "/api/v1/sites", nil, "")
234 if code != http.StatusOK {
235 t.Fatalf("list status %d", code)
236 }
237 if n := len(env["data"].([]any)); n != 1 {
238 t.Fatalf("want 1 site, got %d", n)
239 }
240
241 code, _ = h.do(t, http.MethodPost, "/api/v1/sites/"+itoa(id)+"/action",
242 map[string]string{"action": "start"}, csrf)
243 if code != http.StatusBadRequest {
244 t.Fatalf("static site start should be 400, got %d", code)
245 }
246
247 // Duplicate domain must be rejected with 400.
248 code, env = h.do(t, http.MethodPost, "/api/v1/sites", map[string]any{
249 "name": "dup", "kind": "static", "domains": []string{"example.com"},
250 }, csrf)
251 if code != http.StatusBadRequest {
252 t.Fatalf("duplicate domain accepted: %d %v", code, env)
253 }
254
255 code, _ = h.do(t, http.MethodDelete, "/api/v1/sites/"+itoa(id)+"?remove_files=1", nil, csrf)
256 if code != http.StatusOK {
257 t.Fatalf("delete status %d", code)
258 }
259 if fileExists(conf) {
260 t.Fatal("vhost not removed")
261 }
262 code, _ = h.do(t, http.MethodGet, "/api/v1/sites/"+itoa(id), nil, "")
263 if code != http.StatusNotFound {
264 t.Fatalf("deleted site still visible: %d", code)
265 }
266}
267
268func TestUpdateSiteOptions(t *testing.T) {
269 h := newHarness(t)
270 csrf := h.login(t)
271 _, env := h.do(t, http.MethodPost, "/api/v1/sites", map[string]any{
272 "name": "app", "kind": "node", "domains": []string{"app.example.com"},
273 "start_cmd": "npm start",
274 }, csrf)
275 created := env["data"].(map[string]any)
276 id := int64(created["id"].(float64))
277 if created["port"].(float64) < 8000 {
278 t.Fatalf("port not allocated: %v", created["port"])
279 }
280 code, env := h.do(t, http.MethodPut, "/api/v1/sites/"+itoa(id), map[string]any{
281 "name": "app", "kind": "node", "domains": []string{"app.example.com"},
282 "start_cmd": "npm start", "port": created["port"],
283 "remark": "updated",
284 "options": map[string]any{"security_headers": true, "conn_per_ip": 20,
285 "anti_leech": true, "ip_mode": "allow", "ip_list": []string{"10.0.0.1"}},
286 }, csrf)
287 if code != http.StatusOK {
288 t.Fatalf("update status %d: %v", code, env)
289 }
290 updated := env["data"].(map[string]any)
291 if updated["remark"] != "updated" {
292 t.Fatalf("remark not updated: %v", updated)
293 }
294 code, env = h.do(t, http.MethodGet, "/api/v1/sites/"+itoa(id)+"/config", nil, "")
295 if code != http.StatusOK {
296 t.Fatalf("config status %d", code)
297 }
298 files := env["data"].(map[string]any)["files"].(map[string]any)
299 var found bool
300 for path, content := range files {
301 if strings.HasSuffix(path, "50-ip.conf") && strings.Contains(content.(string), "allow 10.0.0.1;") {
302 found = true
303 }
304 }
305 if !found {
306 t.Fatalf("ip fragment not rendered: %v", files)
307 }
308}
309
310func itoa(v int64) string { return strconv.FormatInt(v, 10) }
311
312func testLogger() *slog.Logger {
313 return slog.New(slog.NewTextHandler(io.Discard, nil))
314}
315
316func fileExists(p string) bool {
317 _, err := os.Stat(p)
318 return err == nil
319}