package main import ( "net/http/httptest" "reflect" "strings" "testing" "git.mchus.pro/mchus/quoteforge/internal/config" "github.com/gin-gonic/gin" ) func TestRequestBoundaryOnApplicationRouters(t *testing.T) { moveToRepoRoot(t) local, connMgr, _ := newAPITestStack(t) if err := local.SaveSettings("db.example", 3306, "example", "example", "example"); err != nil { t.Fatal(err) } cfg := &config.Config{} setConfigDefaults(cfg) runtimeRouter, _, err := setupRouter(cfg, local, connMgr, "example", nil) if err != nil { t.Fatal(err) } setupRouter, err := setupSetupRouter(local, nil) if err != nil { t.Fatal(err) } for name, router := range map[string]*gin.Engine{"setup": setupRouter, "runtime": runtimeRouter} { t.Run(name, func(t *testing.T) { before, err := local.GetSettings() if err != nil { t.Fatal(err) } projects, configs, pending := local.CountProjects(), local.CountConfigurations(), local.CountPendingChanges() for _, tt := range []struct { name, method, path, host, origin, contentType, body string want int }{ {"foreign setup save", "POST", "/setup", "", "https://attacker.example", "application/x-www-form-urlencoded", "host=attacker.example&user=example", 403}, {"foreign setup test", "POST", "/setup/test", "", "https://attacker.example", "application/x-www-form-urlencoded", "host=attacker.example&user=example", 403}, {"rebind settings read", "GET", "/setup/status", "attacker.example:8080", "", "", "", 403}, {"opaque origin", "PUT", "/api/settings/ui", "", "null", "application/json", `{"indicator_mode":"accessible"}`, 403}, {"plain JSON", "PUT", "/api/settings/ui", "", "", "text/plain", `{"indicator_mode":"accessible"}`, 415}, {"saved password destination save", "POST", "/setup", "", "", "application/x-www-form-urlencoded", "host=attacker.example&user=example", 422}, {"saved password destination test", "POST", "/setup/test", "", "", "application/x-www-form-urlencoded", "host=attacker.example&user=example", 422}, {"local read", "GET", "/api/settings/ui", "", "http://127.0.0.1:8080", "", "", 200}, } { t.Run(tt.name, func(t *testing.T) { req := httptest.NewRequest(tt.method, "http://127.0.0.1:8080"+tt.path, strings.NewReader(tt.body)) if tt.host != "" { req.Host = tt.host } req.Header.Set("Origin", tt.origin) req.Header.Set("Content-Type", tt.contentType) w := httptest.NewRecorder() router.ServeHTTP(w, req) if w.Code != tt.want { t.Fatalf("status=%d want=%d body=%s", w.Code, tt.want, w.Body.String()) } }) } after, err := local.GetSettings() if err != nil { t.Fatal(err) } if !reflect.DeepEqual(before, after) || projects != local.CountProjects() || configs != local.CountConfigurations() || pending != local.CountPendingChanges() { t.Fatal("rejected requests changed local state") } }) } }