| // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 |
| 15 | package http |
| 16 |
| 17 | import ( |
| 18 | "encoding/json" |
| 19 | "fmt" |
| 20 | "math" |
| 21 | "net/http" |
| 22 | "net/http/httptest" |
| 23 | "net/url" |
| 24 | "testing" |
| 25 | "time" |
| 26 |
| 27 | "github.com/gorilla/mux" |
| 28 |
| 29 | "github.com/fatedier/frp/pkg/config/types" |
| 30 | v1 "github.com/fatedier/frp/pkg/config/v1" |
| 31 | "github.com/fatedier/frp/pkg/metrics/mem" |
| 32 | httppkg "github.com/fatedier/frp/pkg/util/http" |
| 33 | "github.com/fatedier/frp/server/http/model" |
| 34 | serverproxy "github.com/fatedier/frp/server/proxy" |
| 35 | "github.com/fatedier/frp/server/registry" |
| 36 | ) |
| 37 |
| 38 | type v2EnvelopeForTest[T any] struct { |
| 39 | Code int `json:"code"` |
| 40 | Msg string `json:"msg"` |
| 41 | Data T `json:"data"` |
| 42 | } |
| 43 |
| 44 | type fakeStatsCollector struct { |
| 45 | server *mem.ServerStats |
| 46 | proxies map[string]*mem.ProxyStats |
| 47 | traffic map[string]*mem.ProxyTrafficInfo |
| 48 | pruneable map[string]bool |
| 49 | } |
| 50 |
| 51 | func (f *fakeStatsCollector) GetServer() *mem.ServerStats { |
| 52 | if f.server != nil { |
| 53 | return f.server |
| 54 | } |
| 55 | return &mem.ServerStats{ProxyTypeCounts: map[string]int64{}} |
| 56 | } |
| 57 |
| 58 | func (f *fakeStatsCollector) GetProxiesByType(proxyType string) []*mem.ProxyStats { |
| 59 | items := make([]*mem.ProxyStats, 0) |
| 60 | for _, ps := range f.proxies { |
| 61 | if ps.Type == proxyType { |
| 62 | items = append(items, ps) |
| 63 | } |
| 64 | } |
| 65 | return items |
| 66 | } |
| 67 |
| 68 | func (f *fakeStatsCollector) GetProxiesByTypeAndName(proxyType string, proxyName string) *mem.ProxyStats { |
| 69 | ps := f.proxies[proxyName] |
| 70 | if ps != nil && ps.Type == proxyType { |
| 71 | return ps |
| 72 | } |
| 73 | return nil |
| 74 | } |
| 75 |
| 76 | func (f *fakeStatsCollector) GetProxyByName(proxyName string) *mem.ProxyStats { |
| 77 | return f.proxies[proxyName] |
| 78 | } |
| 79 |
| 80 | func (f *fakeStatsCollector) GetProxyTraffic(name string) *mem.ProxyTrafficInfo { |
| 81 | return f.traffic[name] |
| 82 | } |
| 83 |
| 84 | func (f *fakeStatsCollector) ClearOfflineProxies() (int, int) { |
| 85 | return 0, len(f.proxies) |
| 86 | } |
| 87 |
| 88 | func (f *fakeStatsCollector) PruneOfflineProxies() (int, int) { |
| 89 | total := len(f.proxies) |
| 90 | cleared := 0 |
| 91 | for name := range f.pruneable { |
| 92 | if _, ok := f.proxies[name]; ok { |
| 93 | delete(f.proxies, name) |
| 94 | cleared++ |
| 95 | } |
| 96 | } |
| 97 | f.pruneable = map[string]bool{} |
| 98 | return cleared, total |
| 99 | } |
| 100 |
| 101 | func TestAPIV2SystemInfoEnvelope(t *testing.T) { |
| 102 | oldStatsCollector := mem.StatsCollector |
| 103 | mem.StatsCollector = &fakeStatsCollector{ |
| 104 | server: &mem.ServerStats{ |
| 105 | TotalTrafficIn: 1024, |
| 106 | TotalTrafficOut: 2048, |
| 107 | CurConns: 3, |
| 108 | ClientCounts: 4, |
| 109 | ProxyTypeCounts: map[string]int64{ |
| 110 | "tcp": 2, |
| 111 | "http": 1, |
| 112 | }, |
| 113 | }, |
| 114 | proxies: map[string]*mem.ProxyStats{}, |
| 115 | } |
| 116 | t.Cleanup(func() { |
| 117 | mem.StatsCollector = oldStatsCollector |
| 118 | }) |
| 119 |
| 120 | controller := NewController(&v1.ServerConfig{ |
| 121 | BindPort: 7000, |
| 122 | VhostHTTPPort: 8080, |
| 123 | VhostHTTPSPort: 8443, |
| 124 | TCPMuxHTTPConnectPort: 9000, |
| 125 | KCPBindPort: 7001, |
| 126 | QUICBindPort: 7002, |
| 127 | SubDomainHost: "example.com", |
| 128 | MaxPortsPerClient: 8, |
| 129 | AllowPorts: []types.PortsRange{ |
| 130 | {Start: 1000, End: 1002}, |
| 131 | {Single: 2000}, |
| 132 | }, |
| 133 | Transport: v1.ServerTransportConfig{ |
| 134 | MaxPoolCount: 5, |
| 135 | HeartbeatTimeout: 90, |
| 136 | TLS: v1.TLSServerConfig{ |
| 137 | Force: true, |
| 138 | }, |
| 139 | }, |
| 140 | }, registry.NewClientRegistry(), serverproxy.NewManager()) |
| 141 | router := newV2TestRouter(controller) |
| 142 |
| 143 | resp := performRequest(router, "/api/v2/system/info") |
| 144 | if resp.Code != http.StatusOK { |
| 145 | t.Fatalf("status mismatch, want %d got %d", http.StatusOK, resp.Code) |
| 146 | } |
| 147 |
| 148 | rawResp := decodeResponse[v2EnvelopeForTest[map[string]json.RawMessage]](t, resp) |
| 149 | if rawResp.Code != http.StatusOK || rawResp.Msg != "success" { |
| 150 | t.Fatalf("envelope mismatch: %#v", rawResp) |
| 151 | } |
| 152 | assertRawJSONKeys(t, rawResp.Data, "config", "status", "version") |
| 153 | assertRawJSONKeysFromMessage(t, rawResp.Data["config"], |
| 154 | "allowPortsStr", |
| 155 | "bindPort", |
| 156 | "heartbeatTimeout", |
| 157 | "kcpBindPort", |
| 158 | "maxPoolCount", |
| 159 | "maxPortsPerClient", |
| 160 | "quicBindPort", |
| 161 | "subdomainHost", |
| 162 | "tcpmuxHTTPConnectPort", |
| 163 | "tlsForce", |
| 164 | "vhostHTTPPort", |
| 165 | "vhostHTTPSPort", |
| 166 | ) |
| 167 | assertRawJSONKeysFromMessage(t, rawResp.Data["status"], |
| 168 | "clientCounts", |
| 169 | "curConns", |
| 170 | "proxyTypeCount", |
| 171 | "totalTrafficIn", |
| 172 | "totalTrafficOut", |
| 173 | ) |
| 174 |
| 175 | systemResp := decodeResponse[v2EnvelopeForTest[model.V2SystemInfoResp]](t, resp) |
| 176 | if systemResp.Data.Version == "" { |
| 177 | t.Fatal("version should be set at top level") |
| 178 | } |
| 179 | if systemResp.Data.Config.BindPort != 7000 || |
| 180 | systemResp.Data.Config.VhostHTTPPort != 8080 || |
| 181 | systemResp.Data.Config.VhostHTTPSPort != 8443 || |
| 182 | systemResp.Data.Config.TCPMuxHTTPConnectPort != 9000 || |
| 183 | systemResp.Data.Config.KCPBindPort != 7001 || |
| 184 | systemResp.Data.Config.QUICBindPort != 7002 || |
| 185 | systemResp.Data.Config.SubdomainHost != "example.com" || |
| 186 | systemResp.Data.Config.MaxPoolCount != 5 || |
| 187 | systemResp.Data.Config.MaxPortsPerClient != 8 || |
| 188 | systemResp.Data.Config.HeartbeatTimeout != 90 || |
| 189 | systemResp.Data.Config.AllowPortsStr != "1000-1002,2000" || |
| 190 | !systemResp.Data.Config.TLSForce { |
| 191 | t.Fatalf("config mismatch: %#v", systemResp.Data.Config) |
| 192 | } |
| 193 | if systemResp.Data.Status.TotalTrafficIn != 1024 || |
| 194 | systemResp.Data.Status.TotalTrafficOut != 2048 || |
| 195 | systemResp.Data.Status.CurConns != 3 || |
| 196 | systemResp.Data.Status.ClientCounts != 4 || |
| 197 | systemResp.Data.Status.ProxyTypeCounts["tcp"] != 2 || |
| 198 | systemResp.Data.Status.ProxyTypeCounts["http"] != 1 { |
| 199 | t.Fatalf("status mismatch: %#v", systemResp.Data.Status) |
| 200 | } |
| 201 | } |
| 202 |
| 203 | func TestAPIV2SystemPruneOfflineProxies(t *testing.T) { |
| 204 | oldStatsCollector := mem.StatsCollector |
| 205 | collector := &fakeStatsCollector{ |
| 206 | proxies: map[string]*mem.ProxyStats{ |
| 207 | "tcp-offline": {Name: "tcp-offline", Type: "tcp"}, |
| 208 | "http-offline": {Name: "http-offline", Type: "http"}, |
| 209 | "udp-offline": {Name: "udp-offline", Type: "udp"}, |
| 210 | "tcp-online": {Name: "tcp-online", Type: "tcp"}, |
| 211 | "http-online": {Name: "http-online", Type: "http"}, |
| 212 | "udp-online": {Name: "udp-online", Type: "udp"}, |
| 213 | "stcp-restarted": {Name: "stcp-restarted", Type: "stcp"}, |
| 214 | "xtcp-restarted": {Name: "xtcp-restarted", Type: "xtcp"}, |
| 215 | "sudp-same-time": {Name: "sudp-same-time", Type: "sudp"}, |
| 216 | "tcpmux-running": {Name: "tcpmux-running", Type: "tcpmux"}, |
| 217 | }, |
| 218 | pruneable: map[string]bool{ |
| 219 | "tcp-offline": true, |
| 220 | "http-offline": true, |
| 221 | "udp-offline": true, |
| 222 | }, |
| 223 | } |
| 224 | mem.StatsCollector = collector |
| 225 | t.Cleanup(func() { |
| 226 | mem.StatsCollector = oldStatsCollector |
| 227 | }) |
| 228 |
| 229 | controller := NewController(&v1.ServerConfig{}, registry.NewClientRegistry(), serverproxy.NewManager()) |
| 230 | router := newV2TestRouter(controller) |
| 231 |
| 232 | resp := performRequestWithMethod(router, http.MethodPost, "/api/v2/system/prune?type=offline_proxies") |
| 233 | if resp.Code != http.StatusOK { |
| 234 | t.Fatalf("status mismatch, want %d got %d, body: %s", http.StatusOK, resp.Code, resp.Body.String()) |
| 235 | } |
| 236 | rawResp := decodeResponse[v2EnvelopeForTest[map[string]json.RawMessage]](t, resp) |
| 237 | if rawResp.Code != http.StatusOK || rawResp.Msg != "success" { |
| 238 | t.Fatalf("envelope mismatch: %#v", rawResp) |
| 239 | } |
| 240 | assertRawJSONKeys(t, rawResp.Data, "cleared", "total", "type") |
| 241 | pruneResp := decodeResponse[v2EnvelopeForTest[model.V2SystemPruneResp]](t, resp) |
| 242 | if pruneResp.Data.Type != "offline_proxies" || pruneResp.Data.Cleared != 3 || pruneResp.Data.Total != 10 { |
| 243 | t.Fatalf("prune response mismatch: %#v", pruneResp.Data) |
| 244 | } |
| 245 | if _, ok := collector.proxies["tcp-offline"]; ok { |
| 246 | t.Fatal("pruned proxy statistics should be removed") |
| 247 | } |
| 248 | if _, ok := collector.proxies["tcp-online"]; !ok { |
| 249 | t.Fatal("online proxy statistics should remain") |
| 250 | } |
| 251 |
| 252 | resp = performRequestWithMethod(router, http.MethodPost, "/api/v2/system/prune?type=offline_proxies") |
| 253 | if resp.Code != http.StatusOK { |
| 254 | t.Fatalf("second prune status mismatch, want %d got %d", http.StatusOK, resp.Code) |
| 255 | } |
| 256 | pruneResp = decodeResponse[v2EnvelopeForTest[model.V2SystemPruneResp]](t, resp) |
| 257 | if pruneResp.Data.Cleared != 0 || pruneResp.Data.Total != 7 { |
| 258 | t.Fatalf("second prune response mismatch: %#v", pruneResp.Data) |
| 259 | } |
| 260 | } |
| 261 |
| 262 | func TestAPIV2SystemPruneTypeErrorsUseEnvelope(t *testing.T) { |
| 263 | controller := newV2TestController(t) |
| 264 | router := newV2TestRouter(controller) |
| 265 |
| 266 | resp := performRequestWithMethod(router, http.MethodPost, "/api/v2/system/prune") |
| 267 | if resp.Code != http.StatusBadRequest { |
| 268 | t.Fatalf("missing type status mismatch, want %d got %d", http.StatusBadRequest, resp.Code) |
| 269 | } |
| 270 | errResp := decodeResponse[httppkg.V2Response](t, resp) |
| 271 | if errResp.Code != http.StatusBadRequest || errResp.Msg != "type is required" || errResp.Data != nil { |
| 272 | t.Fatalf("missing type error envelope mismatch: %#v", errResp) |
| 273 | } |
| 274 |
| 275 | resp = performRequestWithMethod(router, http.MethodPost, "/api/v2/system/prune?type=clients") |
| 276 | if resp.Code != http.StatusBadRequest { |
| 277 | t.Fatalf("invalid type status mismatch, want %d got %d", http.StatusBadRequest, resp.Code) |
| 278 | } |
| 279 | errResp = decodeResponse[httppkg.V2Response](t, resp) |
| 280 | if errResp.Code != http.StatusBadRequest || errResp.Msg != "type must be one of offline_proxies" || errResp.Data != nil { |
| 281 | t.Fatalf("invalid type error envelope mismatch: %#v", errResp) |
| 282 | } |
| 283 | } |
| 284 |
| 285 | func TestAPIV2ClientListEnvelopePaginationAndFilters(t *testing.T) { |
| 286 | controller := newV2TestController(t) |
| 287 | router := newV2TestRouter(controller) |
| 288 |
| 289 | resp := performRequest(router, "/api/v2/clients?page=1&pageSize=1") |
| 290 | if resp.Code != http.StatusOK { |
| 291 | t.Fatalf("status mismatch, want %d got %d", http.StatusOK, resp.Code) |
| 292 | } |
| 293 | pageResp := decodeResponse[v2EnvelopeForTest[model.V2PageResp[model.ClientInfoResp]]](t, resp) |
| 294 | if pageResp.Code != http.StatusOK || pageResp.Msg != "success" { |
| 295 | t.Fatalf("envelope mismatch: %#v", pageResp) |
| 296 | } |
| 297 | if pageResp.Data.Total != 3 || pageResp.Data.Page != 1 || pageResp.Data.PageSize != 1 || len(pageResp.Data.Items) != 1 { |
| 298 | t.Fatalf("page data mismatch: %#v", pageResp.Data) |
| 299 | } |
| 300 | if got := pageResp.Data.Items[0].User; got != "" { |
| 301 | t.Fatalf("first sorted user mismatch, want empty got %q", got) |
| 302 | } |
| 303 |
| 304 | resp = performRequest(router, "/api/v2/clients?user=&page=1&pageSize=50") |
| 305 | emptyUserResp := decodeResponse[v2EnvelopeForTest[model.V2PageResp[model.ClientInfoResp]]](t, resp) |
| 306 | if emptyUserResp.Data.Total != 1 || emptyUserResp.Data.Items[0].User != "" { |
| 307 | t.Fatalf("empty user filter mismatch: %#v", emptyUserResp.Data) |
| 308 | } |
| 309 |
| 310 | resp = performRequest(router, "/api/v2/clients?user=alice&status=online&q=alice-host") |
| 311 | aliceResp := decodeResponse[v2EnvelopeForTest[model.V2PageResp[model.ClientInfoResp]]](t, resp) |
| 312 | if aliceResp.Data.Total != 1 || aliceResp.Data.Items[0].User != "alice" { |
| 313 | t.Fatalf("alice filter mismatch: %#v", aliceResp.Data) |
| 314 | } |
| 315 |
| 316 | resp = performRequest(router, "/api/v2/clients?status=offline") |
| 317 | offlineResp := decodeResponse[v2EnvelopeForTest[model.V2PageResp[model.ClientInfoResp]]](t, resp) |
| 318 | if offlineResp.Data.Total != 1 || offlineResp.Data.Items[0].User != "bob" { |
| 319 | t.Fatalf("offline filter mismatch: %#v", offlineResp.Data) |
| 320 | } |
| 321 | } |
| 322 |
| 323 | func TestAPIV2PageParamErrorsUseEnvelope(t *testing.T) { |
| 324 | controller := newV2TestController(t) |
| 325 | router := newV2TestRouter(controller) |
| 326 |
| 327 | resp := performRequest(router, "/api/v2/clients?page=0") |
| 328 | if resp.Code != http.StatusBadRequest { |
| 329 | t.Fatalf("status mismatch, want %d got %d", http.StatusBadRequest, resp.Code) |
| 330 | } |
| 331 | errResp := decodeResponse[httppkg.V2Response](t, resp) |
| 332 | if errResp.Code != http.StatusBadRequest || errResp.Data != nil { |
| 333 | t.Fatalf("error envelope mismatch: %#v", errResp) |
| 334 | } |
| 335 |
| 336 | resp = performRequest(router, "/api/v2/clients?pageSize=201") |
| 337 | if resp.Code != http.StatusBadRequest { |
| 338 | t.Fatalf("status mismatch, want %d got %d", http.StatusBadRequest, resp.Code) |
| 339 | } |
| 340 |
| 341 | resp = performRequest(router, fmt.Sprintf("/api/v2/clients?page=%d&pageSize=2", math.MaxInt)) |
| 342 | if resp.Code != http.StatusBadRequest { |
| 343 | t.Fatalf("status mismatch for overflowing page offset, want %d got %d", http.StatusBadRequest, resp.Code) |
| 344 | } |
| 345 | } |
| 346 |
| 347 | func TestAPIV2ClientDetailEnvelope(t *testing.T) { |
| 348 | controller := newV2TestController(t) |
| 349 | router := newV2TestRouter(controller) |
| 350 |
| 351 | resp := performRequest(router, "/api/v2/clients/alice.client-a") |
| 352 | if resp.Code != http.StatusOK { |
| 353 | t.Fatalf("status mismatch, want %d got %d", http.StatusOK, resp.Code) |
| 354 | } |
| 355 | detailResp := decodeResponse[v2EnvelopeForTest[model.V2ClientDetailResp]](t, resp) |
| 356 | if detailResp.Data.User != "alice" || detailResp.Data.ClientID != "client-a" { |
| 357 | t.Fatalf("client detail mismatch: %#v", detailResp.Data) |
| 358 | } |
| 359 | if detailResp.Data.Status.State != "online" || detailResp.Data.Status.CurConns != 5 || detailResp.Data.Status.ProxyCount != 2 { |
| 360 | t.Fatalf("client detail status mismatch: %#v", detailResp.Data.Status) |
| 361 | } |
| 362 | } |
| 363 |
| 364 | func TestAPIV2ClientDetailEncodedKey(t *testing.T) { |
| 365 | oldStatsCollector := mem.StatsCollector |
| 366 | mem.StatsCollector = &fakeStatsCollector{ |
| 367 | proxies: map[string]*mem.ProxyStats{ |
| 368 | "tcp-url": { |
| 369 | Name: "tcp-url", |
| 370 | Type: "tcp", |
| 371 | User: "url", |
| 372 | ClientID: "client/a?b#c", |
| 373 | CurConns: 7, |
| 374 | }, |
| 375 | }, |
| 376 | } |
| 377 | t.Cleanup(func() { |
| 378 | mem.StatsCollector = oldStatsCollector |
| 379 | }) |
| 380 |
| 381 | clientRegistry := registry.NewClientRegistry() |
| 382 | clientRegistry.Register("url", "client/a?b#c", "run-url", "url-host", "1.0.0", "127.0.0.4", "v2") |
| 383 | controller := NewController(&v1.ServerConfig{}, clientRegistry, serverproxy.NewManager()) |
| 384 | router := newV2TestRouter(controller) |
| 385 |
| 386 | encodedKey := url.PathEscape("url.client/a?b#c") |
| 387 | resp := performRequest(router, "/api/v2/clients/"+encodedKey) |
| 388 | if resp.Code != http.StatusOK { |
| 389 | t.Fatalf("encoded client key status mismatch, want %d got %d, body: %s", http.StatusOK, resp.Code, resp.Body.String()) |
| 390 | } |
| 391 | encodedResp := decodeResponse[v2EnvelopeForTest[model.V2ClientDetailResp]](t, resp) |
| 392 | if encodedResp.Data.User != "url" || encodedResp.Data.ClientID != "client/a?b#c" { |
| 393 | t.Fatalf("encoded client detail mismatch: %#v", encodedResp.Data) |
| 394 | } |
| 395 | if encodedResp.Data.Status.CurConns != 7 || encodedResp.Data.Status.ProxyCount != 1 { |
| 396 | t.Fatalf("encoded client detail status mismatch: %#v", encodedResp.Data.Status) |
| 397 | } |
| 398 | } |
| 399 |
| 400 | func TestAPIV2ProxyListDetailAndUsers(t *testing.T) { |
| 401 | controller := newV2TestController(t) |
| 402 | router := newV2TestRouter(controller) |
| 403 |
| 404 | resp := performRequest(router, "/api/v2/proxies?type=invalid") |
| 405 | if resp.Code != http.StatusBadRequest { |
| 406 | t.Fatalf("invalid proxy type status mismatch, want %d got %d", http.StatusBadRequest, resp.Code) |
| 407 | } |
| 408 | errResp := decodeResponse[httppkg.V2Response](t, resp) |
| 409 | if errResp.Code != http.StatusBadRequest || errResp.Data != nil { |
| 410 | t.Fatalf("invalid proxy type error envelope mismatch: %#v", errResp) |
| 411 | } |
| 412 |
| 413 | resp = performRequest(router, "/api/v2/proxies?type=tcp&user=&page=1&pageSize=50") |
| 414 | proxyResp := decodeResponse[v2EnvelopeForTest[model.V2PageResp[model.V2ProxyResp]]](t, resp) |
| 415 | if proxyResp.Data.Total != 1 { |
| 416 | t.Fatalf("proxy filter total mismatch: %#v", proxyResp.Data) |
| 417 | } |
| 418 | proxyItem := proxyResp.Data.Items[0] |
| 419 | if proxyItem.Name != "tcp-empty" || proxyItem.Spec.Type != "tcp" || proxyItem.User != "" || proxyItem.Status.State != "offline" { |
| 420 | t.Fatalf("proxy item mismatch: %#v", proxyItem) |
| 421 | } |
| 422 | rawProxyResp := decodeResponse[v2EnvelopeForTest[model.V2PageResp[map[string]json.RawMessage]]](t, resp) |
| 423 | assertRawJSONKeys(t, rawProxyResp.Data.Items[0], "clientID", "name", "spec", "status", "user") |
| 424 | var rawListSpec map[string]json.RawMessage |
| 425 | if err := json.Unmarshal(rawProxyResp.Data.Items[0]["spec"], &rawListSpec); err != nil { |
| 426 | t.Fatalf("unmarshal list proxy spec failed: %v", err) |
| 427 | } |
| 428 | assertRawJSONKeys(t, rawListSpec, "tcp", "type") |
| 429 | assertRawJSONKeysFromMessage(t, rawListSpec["tcp"]) |
| 430 |
| 431 | resp = performRequest(router, "/api/v2/proxies/tcp-alice") |
| 432 | rawProxyDetailResp := decodeResponse[v2EnvelopeForTest[map[string]json.RawMessage]](t, resp) |
| 433 | assertRawJSONKeysFromMessage(t, rawProxyDetailResp.Data["status"], |
| 434 | "curConns", |
| 435 | "lastCloseAt", |
| 436 | "lastStartAt", |
| 437 | "phase", |
| 438 | "todayTrafficIn", |
| 439 | "todayTrafficOut", |
| 440 | ) |
| 441 | proxyDetailResp := decodeResponse[v2EnvelopeForTest[model.V2ProxyResp]](t, resp) |
| 442 | if proxyDetailResp.Data.Name != "tcp-alice" || proxyDetailResp.Data.User != "alice" { |
| 443 | t.Fatalf("proxy detail mismatch: %#v", proxyDetailResp.Data) |
| 444 | } |
| 445 | assertRawJSONKeys(t, rawProxyDetailResp.Data, "clientID", "name", "spec", "status", "user") |
| 446 | var rawDetailSpec map[string]json.RawMessage |
| 447 | if err := json.Unmarshal(rawProxyDetailResp.Data["spec"], &rawDetailSpec); err != nil { |
| 448 | t.Fatalf("unmarshal detail proxy spec failed: %v", err) |
| 449 | } |
| 450 | assertRawJSONKeys(t, rawDetailSpec, "tcp", "type") |
| 451 | assertRawJSONKeysFromMessage(t, rawDetailSpec["tcp"]) |
| 452 | if proxyDetailResp.Data.Status.LastStartAt != 1783504200 || proxyDetailResp.Data.Status.LastCloseAt != 1783504300 { |
| 453 | t.Fatalf("proxy detail timestamp mismatch: %#v", proxyDetailResp.Data.Status) |
| 454 | } |
| 455 |
| 456 | resp = performRequest(router, "/api/v2/users?page=1&pageSize=50") |
| 457 | userResp := decodeResponse[v2EnvelopeForTest[model.V2PageResp[model.V2UserResp]]](t, resp) |
| 458 | if userResp.Data.Total != 3 { |
| 459 | t.Fatalf("user total mismatch: %#v", userResp.Data) |
| 460 | } |
| 461 | expectedProxyCounts := map[string]int{ |
| 462 | "": 1, |
| 463 | "alice": 2, |
| 464 | "bob": 1, |
| 465 | } |
| 466 | for _, item := range userResp.Data.Items { |
| 467 | if item.ClientCount != 1 || item.ProxyCount != expectedProxyCounts[item.User] { |
| 468 | t.Fatalf("user counts mismatch: %#v", item) |
| 469 | } |
| 470 | } |
| 471 | } |
| 472 |
| 473 | func TestAPIV2ProxyTrafficEnvelopeSchemaAndHistory(t *testing.T) { |
| 474 | oldStatsCollector := mem.StatsCollector |
| 475 | mem.StatsCollector = &fakeStatsCollector{ |
| 476 | proxies: map[string]*mem.ProxyStats{ |
| 477 | "ssh": {Name: "ssh", Type: "tcp"}, |
| 478 | }, |
| 479 | traffic: map[string]*mem.ProxyTrafficInfo{ |
| 480 | "ssh": { |
| 481 | Name: "ssh", |
| 482 | TrafficIn: []int64{70, 60, 50, 40, 30, 20, 10}, |
| 483 | TrafficOut: []int64{700, 600, 500, 400, 300, 200, 100}, |
| 484 | }, |
| 485 | }, |
| 486 | } |
| 487 | t.Cleanup(func() { |
| 488 | mem.StatsCollector = oldStatsCollector |
| 489 | }) |
| 490 |
| 491 | controller := NewController(&v1.ServerConfig{}, registry.NewClientRegistry(), serverproxy.NewManager()) |
| 492 | router := newV2TestRouter(controller) |
| 493 |
| 494 | resp := performRequest(router, "/api/v2/proxies/ssh/traffic") |
| 495 | if resp.Code != http.StatusOK { |
| 496 | t.Fatalf("status mismatch, want %d got %d, body: %s", http.StatusOK, resp.Code, resp.Body.String()) |
| 497 | } |
| 498 | rawResp := decodeResponse[v2EnvelopeForTest[map[string]json.RawMessage]](t, resp) |
| 499 | if rawResp.Code != http.StatusOK || rawResp.Msg != "success" { |
| 500 | t.Fatalf("envelope mismatch: %#v", rawResp) |
| 501 | } |
| 502 | assertRawJSONKeys(t, rawResp.Data, "granularity", "history", "name", "unit") |
| 503 |
| 504 | trafficResp := decodeResponse[v2EnvelopeForTest[model.V2ProxyTrafficResp]](t, resp) |
| 505 | if trafficResp.Data.Name != "ssh" || trafficResp.Data.Unit != "bytes" || trafficResp.Data.Granularity != "day" { |
| 506 | t.Fatalf("traffic metadata mismatch: %#v", trafficResp.Data) |
| 507 | } |
| 508 | if len(trafficResp.Data.History) != 7 { |
| 509 | t.Fatalf("history length mismatch, want 7 got %d: %#v", len(trafficResp.Data.History), trafficResp.Data.History) |
| 510 | } |
| 511 |
| 512 | wantIn := []int64{10, 20, 30, 40, 50, 60, 70} |
| 513 | wantOut := []int64{100, 200, 300, 400, 500, 600, 700} |
| 514 | var prevDate time.Time |
| 515 | for i, point := range trafficResp.Data.History { |
| 516 | assertRawJSONKeysFromMessage(t, mustMarshalJSON(t, point), "date", "trafficIn", "trafficOut") |
| 517 | if point.TrafficIn != wantIn[i] || point.TrafficOut != wantOut[i] { |
| 518 | t.Fatalf("history[%d] traffic mismatch: %#v", i, point) |
| 519 | } |
| 520 | parsedDate, err := time.Parse(time.DateOnly, point.Date) |
| 521 | if err != nil { |
| 522 | t.Fatalf("history[%d] date should be yyyy-mm-dd, got %q: %v", i, point.Date, err) |
| 523 | } |
| 524 | if i > 0 && !parsedDate.Equal(prevDate.AddDate(0, 0, 1)) { |
| 525 | t.Fatalf("history dates should be oldest to newest, got %s after %s", point.Date, prevDate.Format(time.DateOnly)) |
| 526 | } |
| 527 | prevDate = parsedDate |
| 528 | } |
| 529 | } |
| 530 |
| 531 | func TestAPIV2ProxyTrafficNotFoundEnvelope(t *testing.T) { |
| 532 | controller := newV2TestController(t) |
| 533 | router := newV2TestRouter(controller) |
| 534 |
| 535 | resp := performRequest(router, "/api/v2/proxies/missing/traffic") |
| 536 | if resp.Code != http.StatusNotFound { |
| 537 | t.Fatalf("status mismatch, want %d got %d, body: %s", http.StatusNotFound, resp.Code, resp.Body.String()) |
| 538 | } |
| 539 | errResp := decodeResponse[httppkg.V2Response](t, resp) |
| 540 | if errResp.Code != http.StatusNotFound || errResp.Msg != "no proxy info found" || errResp.Data != nil { |
| 541 | t.Fatalf("not found envelope mismatch: %#v", errResp) |
| 542 | } |
| 543 | } |
| 544 |
| 545 | func TestAPIV2ProxyDetailAndTrafficEncodedName(t *testing.T) { |
| 546 | name := "folder/ssh?x#y" |
| 547 | oldStatsCollector := mem.StatsCollector |
| 548 | mem.StatsCollector = &fakeStatsCollector{ |
| 549 | proxies: map[string]*mem.ProxyStats{ |
| 550 | name: {Name: name, Type: "tcp", User: "encoded"}, |
| 551 | }, |
| 552 | traffic: map[string]*mem.ProxyTrafficInfo{ |
| 553 | name: { |
| 554 | Name: name, |
| 555 | TrafficIn: []int64{1}, |
| 556 | TrafficOut: []int64{2}, |
| 557 | }, |
| 558 | }, |
| 559 | } |
| 560 | t.Cleanup(func() { |
| 561 | mem.StatsCollector = oldStatsCollector |
| 562 | }) |
| 563 |
| 564 | controller := NewController(&v1.ServerConfig{}, registry.NewClientRegistry(), serverproxy.NewManager()) |
| 565 | router := newV2TestRouter(controller) |
| 566 | encodedName := url.PathEscape(name) |
| 567 |
| 568 | resp := performRequest(router, "/api/v2/proxies/"+encodedName) |
| 569 | if resp.Code != http.StatusOK { |
| 570 | t.Fatalf("encoded proxy detail status mismatch, want %d got %d, body: %s", http.StatusOK, resp.Code, resp.Body.String()) |
| 571 | } |
| 572 | detailResp := decodeResponse[v2EnvelopeForTest[model.V2ProxyResp]](t, resp) |
| 573 | if detailResp.Data.Name != name || detailResp.Data.User != "encoded" { |
| 574 | t.Fatalf("encoded proxy detail mismatch: %#v", detailResp.Data) |
| 575 | } |
| 576 |
| 577 | resp = performRequest(router, "/api/v2/proxies/"+encodedName+"/traffic") |
| 578 | if resp.Code != http.StatusOK { |
| 579 | t.Fatalf("encoded traffic status mismatch, want %d got %d, body: %s", http.StatusOK, resp.Code, resp.Body.String()) |
| 580 | } |
| 581 | trafficResp := decodeResponse[v2EnvelopeForTest[model.V2ProxyTrafficResp]](t, resp) |
| 582 | if trafficResp.Data.Name != name { |
| 583 | t.Fatalf("encoded traffic name mismatch: %#v", trafficResp.Data) |
| 584 | } |
| 585 | if got := trafficResp.Data.History[len(trafficResp.Data.History)-1]; got.TrafficIn != 1 || got.TrafficOut != 2 { |
| 586 | t.Fatalf("encoded traffic latest point mismatch: %#v", got) |
| 587 | } |
| 588 | } |
| 589 |
| 590 | func TestAPIV2ProxyTrafficInvalidEncodedNameUses400Envelope(t *testing.T) { |
| 591 | controller := newV2TestController(t) |
| 592 | handler := httppkg.MakeHTTPHandlerFuncV2(controller.APIV2ProxyTraffic) |
| 593 | req := httptest.NewRequest(http.MethodGet, "/api/v2/proxies/%25ZZ/traffic", nil) |
| 594 | req = mux.SetURLVars(req, map[string]string{"name": "%ZZ"}) |
| 595 | resp := httptest.NewRecorder() |
| 596 | handler.ServeHTTP(resp, req) |
| 597 |
| 598 | if resp.Code != http.StatusBadRequest { |
| 599 | t.Fatalf("status mismatch, want %d got %d, body: %s", http.StatusBadRequest, resp.Code, resp.Body.String()) |
| 600 | } |
| 601 | errResp := decodeResponse[httppkg.V2Response](t, resp) |
| 602 | if errResp.Code != http.StatusBadRequest || errResp.Msg != "invalid proxy name" || errResp.Data != nil { |
| 603 | t.Fatalf("invalid encoded name envelope mismatch: %#v", errResp) |
| 604 | } |
| 605 | } |
| 606 |
| 607 | func TestMatchV2ProxyQueryMatchesSpecFields(t *testing.T) { |
| 608 | tests := []struct { |
| 609 | name string |
| 610 | item model.V2ProxyResp |
| 611 | q string |
| 612 | want bool |
| 613 | }{ |
| 614 | { |
| 615 | name: "tcp remote port", |
| 616 | item: model.V2ProxyResp{Name: "tcp-proxy", Spec: model.V2ProxySpec{ |
| 617 | Type: "tcp", |
| 618 | TCP: &model.V2TCPProxySpec{RemotePort: v2TestIntPtr(6000)}, |
| 619 | }}, |
| 620 | q: "6000", |
| 621 | want: true, |
| 622 | }, |
| 623 | { |
| 624 | name: "udp remote port", |
| 625 | item: model.V2ProxyResp{Name: "udp-proxy", Spec: model.V2ProxySpec{ |
| 626 | Type: "udp", |
| 627 | UDP: &model.V2UDPProxySpec{RemotePort: v2TestIntPtr(7000)}, |
| 628 | }}, |
| 629 | q: "7000", |
| 630 | want: true, |
| 631 | }, |
| 632 | { |
| 633 | name: "remote port does not match colon form", |
| 634 | item: model.V2ProxyResp{Name: "tcp-proxy", Spec: model.V2ProxySpec{ |
| 635 | Type: "tcp", |
| 636 | TCP: &model.V2TCPProxySpec{RemotePort: v2TestIntPtr(6000)}, |
| 637 | }}, |
| 638 | q: ":6000", |
| 639 | want: false, |
| 640 | }, |
| 641 | { |
| 642 | name: "http custom domain", |
| 643 | item: model.V2ProxyResp{Name: "http-proxy", Spec: model.V2ProxySpec{ |
| 644 | Type: "http", |
| 645 | HTTP: &model.V2HTTPProxySpec{CustomDomains: []string{"app.example.com"}}, |
| 646 | }}, |
| 647 | q: "app.example.com", |
| 648 | want: true, |
| 649 | }, |
| 650 | { |
| 651 | name: "https subdomain", |
| 652 | item: model.V2ProxyResp{Name: "https-proxy", Spec: model.V2ProxySpec{ |
| 653 | Type: "https", |
| 654 | HTTPS: &model.V2HTTPSProxySpec{Subdomain: "portal"}, |
| 655 | }}, |
| 656 | q: "portal", |
| 657 | want: true, |
| 658 | }, |
| 659 | { |
| 660 | name: "subdomain does not match expanded host", |
| 661 | item: model.V2ProxyResp{Name: "https-proxy", Spec: model.V2ProxySpec{ |
| 662 | Type: "https", |
| 663 | HTTPS: &model.V2HTTPSProxySpec{Subdomain: "portal"}, |
| 664 | }}, |
| 665 | q: "portal.example.com", |
| 666 | want: false, |
| 667 | }, |
| 668 | { |
| 669 | name: "tcpmux custom domain", |
| 670 | item: model.V2ProxyResp{Name: "tcpmux-proxy", Spec: model.V2ProxySpec{ |
| 671 | Type: "tcpmux", |
| 672 | TCPMux: &model.V2TCPMuxProxySpec{CustomDomains: []string{"mux.example.com"}}, |
| 673 | }}, |
| 674 | q: "mux.example.com", |
| 675 | want: true, |
| 676 | }, |
| 677 | { |
| 678 | name: "offline shell does not match online spec fields", |
| 679 | item: model.V2ProxyResp{Name: "offline-proxy", Spec: model.V2ProxySpec{ |
| 680 | Type: "tcp", |
| 681 | TCP: &model.V2TCPProxySpec{}, |
| 682 | }}, |
| 683 | q: "6000", |
| 684 | want: false, |
| 685 | }, |
| 686 | { |
| 687 | name: "offline shell does not contribute zero remote port", |
| 688 | item: model.V2ProxyResp{Name: "offline-proxy", Spec: model.V2ProxySpec{ |
| 689 | Type: "tcp", |
| 690 | TCP: &model.V2TCPProxySpec{}, |
| 691 | }}, |
| 692 | q: "0", |
| 693 | want: false, |
| 694 | }, |
| 695 | } |
| 696 |
| 697 | for _, tt := range tests { |
| 698 | t.Run(tt.name, func(t *testing.T) { |
| 699 | if got := matchV2ProxyQuery(tt.item, tt.q); got != tt.want { |
| 700 | t.Fatalf("matchV2ProxyQuery() = %v, want %v", got, tt.want) |
| 701 | } |
| 702 | }) |
| 703 | } |
| 704 | } |
| 705 |
| 706 | func TestLegacyAPIResponsesRemainBare(t *testing.T) { |
| 707 | controller := newV2TestController(t) |
| 708 | router := newV2TestRouter(controller) |
| 709 |
| 710 | resp := performRequest(router, "/api/serverinfo") |
| 711 | var serverInfo model.ServerInfoResp |
| 712 | if err := json.Unmarshal(resp.Body.Bytes(), &serverInfo); err != nil { |
| 713 | t.Fatalf("legacy serverinfo should be a bare object: %v, body: %s", err, resp.Body.String()) |
| 714 | } |
| 715 | if serverInfo.Version == "" { |
| 716 | t.Fatal("legacy serverinfo version should be set") |
| 717 | } |
| 718 | var serverInfoRaw map[string]json.RawMessage |
| 719 | if err := json.Unmarshal(resp.Body.Bytes(), &serverInfoRaw); err != nil { |
| 720 | t.Fatalf("unmarshal legacy serverinfo object failed: %v", err) |
| 721 | } |
| 722 | if _, ok := serverInfoRaw["data"]; ok { |
| 723 | t.Fatalf("legacy serverinfo should not use v2 envelope: %s", resp.Body.String()) |
| 724 | } |
| 725 | if _, ok := serverInfoRaw["config"]; ok { |
| 726 | t.Fatalf("legacy serverinfo should stay flat, got config in: %s", resp.Body.String()) |
| 727 | } |
| 728 |
| 729 | resp = performRequest(router, "/api/clients") |
| 730 | var clients []model.ClientInfoResp |
| 731 | if err := json.Unmarshal(resp.Body.Bytes(), &clients); err != nil { |
| 732 | t.Fatalf("legacy clients should be a bare array: %v, body: %s", err, resp.Body.String()) |
| 733 | } |
| 734 | if len(clients) != 3 { |
| 735 | t.Fatalf("legacy clients total mismatch, want 3 got %d", len(clients)) |
| 736 | } |
| 737 |
| 738 | resp = performRequest(router, "/api/proxy/tcp") |
| 739 | var proxies model.GetProxyInfoResp |
| 740 | if err := json.Unmarshal(resp.Body.Bytes(), &proxies); err != nil { |
| 741 | t.Fatalf("legacy proxy response should be {proxies}: %v, body: %s", err, resp.Body.String()) |
| 742 | } |
| 743 | if len(proxies.Proxies) != 2 { |
| 744 | t.Fatalf("legacy tcp proxy total mismatch, want 2 got %d", len(proxies.Proxies)) |
| 745 | } |
| 746 | var envelope httppkg.V2Response |
| 747 | if err := json.Unmarshal(resp.Body.Bytes(), &envelope); err == nil && envelope.Code != 0 { |
| 748 | t.Fatalf("legacy proxy response should not use v2 envelope: %#v", envelope) |
| 749 | } |
| 750 |
| 751 | resp = performRequest(router, "/api/traffic/tcp-alice") |
| 752 | var traffic model.GetProxyTrafficResp |
| 753 | if err := json.Unmarshal(resp.Body.Bytes(), &traffic); err != nil { |
| 754 | t.Fatalf("legacy traffic should be a bare object: %v, body: %s", err, resp.Body.String()) |
| 755 | } |
| 756 | if traffic.Name != "tcp-alice" || |
| 757 | len(traffic.TrafficIn) != 2 || traffic.TrafficIn[0] != 7 || traffic.TrafficIn[1] != 6 || |
| 758 | len(traffic.TrafficOut) != 2 || traffic.TrafficOut[0] != 70 || traffic.TrafficOut[1] != 60 { |
| 759 | t.Fatalf("legacy traffic should preserve today-first arrays, got: %#v", traffic) |
| 760 | } |
| 761 | var trafficRaw map[string]json.RawMessage |
| 762 | if err := json.Unmarshal(resp.Body.Bytes(), &trafficRaw); err != nil { |
| 763 | t.Fatalf("unmarshal legacy traffic object failed: %v", err) |
| 764 | } |
| 765 | if _, ok := trafficRaw["data"]; ok { |
| 766 | t.Fatalf("legacy traffic should not use v2 envelope: %s", resp.Body.String()) |
| 767 | } |
| 768 | } |
| 769 |
| 770 | func v2TestIntPtr(value int) *int { |
| 771 | return &value |
| 772 | } |
| 773 |
| 774 | func newV2TestController(t *testing.T) *Controller { |
| 775 | t.Helper() |
| 776 |
| 777 | oldStatsCollector := mem.StatsCollector |
| 778 | mem.StatsCollector = &fakeStatsCollector{ |
| 779 | proxies: map[string]*mem.ProxyStats{ |
| 780 | "tcp-empty": { |
| 781 | Name: "tcp-empty", |
| 782 | Type: "tcp", |
| 783 | User: "", |
| 784 | ClientID: "legacy-client", |
| 785 | TodayTrafficIn: 10, |
| 786 | TodayTrafficOut: 20, |
| 787 | CurConns: 1, |
| 788 | }, |
| 789 | "tcp-alice": { |
| 790 | Name: "tcp-alice", |
| 791 | Type: "tcp", |
| 792 | User: "alice", |
| 793 | ClientID: "client-a", |
| 794 | TodayTrafficIn: 30, |
| 795 | TodayTrafficOut: 40, |
| 796 | CurConns: 2, |
| 797 | LastStartTime: "07-08 12:30:00", |
| 798 | LastCloseTime: "07-08 12:31:40", |
| 799 | LastStartAt: 1783504200, |
| 800 | LastCloseAt: 1783504300, |
| 801 | }, |
| 802 | "http-alice": { |
| 803 | Name: "http-alice", |
| 804 | Type: "http", |
| 805 | User: "alice", |
| 806 | ClientID: "client-a", |
| 807 | CurConns: 3, |
| 808 | }, |
| 809 | "udp-bob": { |
| 810 | Name: "udp-bob", |
| 811 | Type: "udp", |
| 812 | User: "bob", |
| 813 | ClientID: "client-b", |
| 814 | }, |
| 815 | }, |
| 816 | traffic: map[string]*mem.ProxyTrafficInfo{ |
| 817 | "tcp-alice": { |
| 818 | Name: "tcp-alice", |
| 819 | TrafficIn: []int64{7, 6}, |
| 820 | TrafficOut: []int64{70, 60}, |
| 821 | }, |
| 822 | }, |
| 823 | } |
| 824 | t.Cleanup(func() { |
| 825 | mem.StatsCollector = oldStatsCollector |
| 826 | }) |
| 827 |
| 828 | clientRegistry := registry.NewClientRegistry() |
| 829 | clientRegistry.Register("", "legacy-client", "run-empty", "empty-host", "1.0.0", "127.0.0.1", "v1") |
| 830 | clientRegistry.Register("alice", "client-a", "run-a", "alice-host", "1.0.0", "127.0.0.2", "v2") |
| 831 | clientRegistry.Register("bob", "client-b", "run-b", "bob-host", "1.0.0", "127.0.0.3", "v1") |
| 832 | clientRegistry.MarkOfflineByRunID("run-b") |
| 833 |
| 834 | return NewController(&v1.ServerConfig{}, clientRegistry, serverproxy.NewManager()) |
| 835 | } |
| 836 |
| 837 | func newV2TestRouter(controller *Controller) *mux.Router { |
| 838 | router := mux.NewRouter() |
| 839 | router.HandleFunc("/api/v2/users", httppkg.MakeHTTPHandlerFuncV2(controller.APIV2UserList)).Methods(http.MethodGet) |
| 840 | router.HandleFunc("/api/v2/system/info", httppkg.MakeHTTPHandlerFuncV2(controller.APIV2SystemInfo)).Methods(http.MethodGet) |
| 841 | router.HandleFunc("/api/v2/system/prune", httppkg.MakeHTTPHandlerFuncV2(controller.APIV2SystemPrune)).Methods(http.MethodPost) |
| 842 | router.HandleFunc("/api/v2/clients", httppkg.MakeHTTPHandlerFuncV2(controller.APIV2ClientList)).Methods(http.MethodGet) |
| 843 | encodedPathRouter := router.NewRoute().Subrouter() |
| 844 | encodedPathRouter.UseEncodedPath() |
| 845 | encodedPathRouter.HandleFunc("/api/v2/clients/{key}", httppkg.MakeHTTPHandlerFuncV2(controller.APIV2ClientDetail)).Methods(http.MethodGet) |
| 846 | router.HandleFunc("/api/v2/proxies", httppkg.MakeHTTPHandlerFuncV2(controller.APIV2ProxyList)).Methods(http.MethodGet) |
| 847 | encodedPathRouter.HandleFunc("/api/v2/proxies/{name}/traffic", httppkg.MakeHTTPHandlerFuncV2(controller.APIV2ProxyTraffic)).Methods(http.MethodGet) |
| 848 | encodedPathRouter.HandleFunc("/api/v2/proxies/{name}", httppkg.MakeHTTPHandlerFuncV2(controller.APIV2ProxyDetail)).Methods(http.MethodGet) |
| 849 | router.HandleFunc("/api/serverinfo", httppkg.MakeHTTPHandlerFunc(controller.APIServerInfo)).Methods(http.MethodGet) |
| 850 | router.HandleFunc("/api/clients", httppkg.MakeHTTPHandlerFunc(controller.APIClientList)).Methods(http.MethodGet) |
| 851 | router.HandleFunc("/api/proxy/{type}", httppkg.MakeHTTPHandlerFunc(controller.APIProxyByType)).Methods(http.MethodGet) |
| 852 | router.HandleFunc("/api/traffic/{name}", httppkg.MakeHTTPHandlerFunc(controller.APIProxyTraffic)).Methods(http.MethodGet) |
| 853 | return router |
| 854 | } |
| 855 |
| 856 | func performRequest(handler http.Handler, target string) *httptest.ResponseRecorder { |
| 857 | return performRequestWithMethod(handler, http.MethodGet, target) |
| 858 | } |
| 859 |
| 860 | func performRequestWithMethod(handler http.Handler, method, target string) *httptest.ResponseRecorder { |
| 861 | req := httptest.NewRequest(method, target, nil) |
| 862 | resp := httptest.NewRecorder() |
| 863 | handler.ServeHTTP(resp, req) |
| 864 | return resp |
| 865 | } |
| 866 |
| 867 | func decodeResponse[T any](t *testing.T, resp *httptest.ResponseRecorder) T { |
| 868 | t.Helper() |
| 869 |
| 870 | var out T |
| 871 | if err := json.Unmarshal(resp.Body.Bytes(), &out); err != nil { |
| 872 | t.Fatalf("unmarshal response failed: %v, body: %s", err, resp.Body.String()) |
| 873 | } |
| 874 | return out |
| 875 | } |
| 876 |
| 877 | func assertRawJSONKeys(t *testing.T, raw map[string]json.RawMessage, want ...string) { |
| 878 | t.Helper() |
| 879 |
| 880 | if len(raw) != len(want) { |
| 881 | t.Fatalf("json keys mismatch, want %v got %v", want, raw) |
| 882 | } |
| 883 | for _, key := range want { |
| 884 | if _, ok := raw[key]; !ok { |
| 885 | t.Fatalf("json key %q missing from %v", key, raw) |
| 886 | } |
| 887 | } |
| 888 | } |
| 889 |
| 890 | func assertRawJSONKeysFromMessage(t *testing.T, raw json.RawMessage, want ...string) { |
| 891 | t.Helper() |
| 892 |
| 893 | var out map[string]json.RawMessage |
| 894 | if err := json.Unmarshal(raw, &out); err != nil { |
| 895 | t.Fatalf("unmarshal raw json object failed: %v, body: %s", err, string(raw)) |
| 896 | } |
| 897 | assertRawJSONKeys(t, out, want...) |
| 898 | } |
| 899 |
| 900 | func mustMarshalJSON(t *testing.T, value any) json.RawMessage { |
| 901 | t.Helper() |
| 902 |
| 903 | out, err := json.Marshal(value) |
| 904 | if err != nil { |
| 905 | t.Fatalf("marshal json failed: %v", err) |
| 906 | } |
| 907 | return out |
| 908 | } |