package server import ( "net/http" "net/http/httptest" "strings" "testing" "managed-portal/internal/webdevice" ) func TestWebDeviceHandlers(t *testing.T) { t.Parallel() t.Run("GET /api/web-devices/scan", func(t *testing.T) { srv := New(nil) svc := webdevice.NewService() svc.SetInterfaceGetter(func() ([]webdevice.InterfaceInfo, error) { return []webdevice.InterfaceInfo{{ Name: "eth0", IP: "10.8.0.14", Netmask: "255.255.255.0", }}, nil }) svc.SetTCPScanner(func(ip, netmask string, port int, excludeIPs map[string]bool) ([]webdevice.TCPDevice, error) { return []webdevice.TCPDevice{{IP: "192.168.1.124", Port: 80}}, nil }) svc.SetForwarderFactory(func(ip string, port int, listenAddress, targetAddress string) (*webdevice.WebDeviceForwarder, error) { return nil, nil }) srv.webDeviceSvc = svc recorder := httptest.NewRecorder() req := httptest.NewRequest(http.MethodGet, "http://10.8.0.14:13000/api/web-devices/scan", nil) srv.engine.ServeHTTP(recorder, req) if recorder.Code != http.StatusOK { t.Fatalf("status = %d body = %s", recorder.Code, recorder.Body.String()) } if !strings.Contains(recorder.Body.String(), "192.168.1.124") { t.Fatalf("scan response = %s", recorder.Body.String()) } }) t.Run("ANY /proxy/web/:ip/*proxyPath rejects unscanned IP", func(t *testing.T) { srv := New(nil) recorder := httptest.NewRecorder() req := httptest.NewRequest(http.MethodGet, "http://portal/proxy/web/192.168.1.124/", nil) srv.engine.ServeHTTP(recorder, req) if recorder.Code != http.StatusForbidden { t.Fatalf("status = %d body = %s", recorder.Code, recorder.Body.String()) } }) t.Run("ANY /proxy/web/:ip/*proxyPath proxies allowed IP", func(t *testing.T) { upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/html") _, _ = w.Write([]byte(``)) })) defer upstream.Close() srv := New(nil) svc := webdevice.NewService() svc.AllowIP("192.168.1.124") svc.SetProxyTargetResolver(func(ip string) string { return upstream.URL }) srv.webDeviceSvc = svc recorder := httptest.NewRecorder() req := httptest.NewRequest(http.MethodGet, "http://portal/proxy/web/192.168.1.124/", nil) srv.engine.ServeHTTP(recorder, req) if recorder.Code != http.StatusOK { t.Fatalf("status = %d body = %s", recorder.Code, recorder.Body.String()) } if !strings.Contains(recorder.Body.String(), "/proxy/web/192.168.1.124/doc/logo.png") { t.Fatalf("proxy response = %s", recorder.Body.String()) } }) }