- Implemented enhanced logic in `isWebSocketUpgrade` to accurately determine WebSocket upgrade requests by checking both "Connection" and "Upgrade" headers. - Added a new test function `TestIsWebSocketUpgrade` to validate the WebSocket upgrade detection logic, ensuring correct behavior for various header configurations.
57 lines
1.7 KiB
Go
57 lines
1.7 KiB
Go
package proxy
|
|
|
|
import (
|
|
"context"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"net/url"
|
|
"testing"
|
|
)
|
|
|
|
func TestMihomoForwardRewritesPathAndAuth(t *testing.T) {
|
|
target, err := url.Parse("http://127.0.0.1:9090")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
cap := &captureTransport{}
|
|
h := NewMihomoForward(target, "/api/mtg/mihomo", "Bearer testsecret", cap, nil)
|
|
|
|
req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "http://gw/api/mtg/mihomo/proxies", nil)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
req.Header.Set("Authorization", "Bearer client-should-not-forward")
|
|
req.Header.Set("Host", "public-gateway.example:8888")
|
|
h.ServeHTTP(httptest.NewRecorder(), req)
|
|
|
|
if cap.got == nil {
|
|
t.Fatal("no outgoing request captured")
|
|
}
|
|
if got, want := cap.got.Host, "127.0.0.1:9090"; got != want {
|
|
t.Fatalf("Host: got %q want %q (upstream must not see client Host)", got, want)
|
|
}
|
|
if got := cap.got.Header.Get("Authorization"); got != "Bearer testsecret" {
|
|
t.Fatalf("Authorization: got %q want Bearer testsecret", got)
|
|
}
|
|
want, err := url.Parse("http://127.0.0.1:9090/proxies")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
assertSameURL(t, cap.got.URL, want)
|
|
}
|
|
|
|
func TestIsWebSocketUpgrade(t *testing.T) {
|
|
r1 := httptest.NewRequest(http.MethodGet, "http://gw/api/mtg/mihomo/traffic", nil)
|
|
r1.Header.Set("Connection", "keep-alive, Upgrade")
|
|
r1.Header.Set("Upgrade", "websocket")
|
|
if !isWebSocketUpgrade(r1) {
|
|
t.Fatal("expected websocket upgrade for tokenized headers")
|
|
}
|
|
|
|
r2 := httptest.NewRequest(http.MethodGet, "http://gw/api/mtg/mihomo/traffic", nil)
|
|
r2.Header.Set("Upgrade", "websocket")
|
|
if isWebSocketUpgrade(r2) {
|
|
t.Fatal("expected non-websocket when Connection lacks upgrade")
|
|
}
|
|
}
|