File
Blob: integrations/waf_test.go
| 1 | package integrations |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "crypto/tls" |
| 7 | "encoding/json" |
| 8 | "fmt" |
| 9 | "io" |
| 10 | "net" |
| 11 | "net/http" |
| 12 | "net/http/httptest" |
| 13 | "net/http/httptrace" |
| 14 | "net/textproto" |
| 15 | "net/url" |
| 16 | "os" |
| 17 | "path/filepath" |
| 18 | "strings" |
| 19 | "sync/atomic" |
| 20 | "testing" |
| 21 | "time" |
| 22 | |
| 23 | clientcmd "go.miragespace.co/specter/cmd/client" |
| 24 | servercmd "go.miragespace.co/specter/cmd/server" |
| 25 | "go.miragespace.co/specter/spec/protocol" |
| 26 | "go.miragespace.co/specter/waf" |
| 27 | |
| 28 | "github.com/gorilla/websocket" |
| 29 | "github.com/quic-go/quic-go" |
| 30 | "github.com/quic-go/quic-go/http3" |
| 31 | "github.com/stretchr/testify/require" |
| 32 | "google.golang.org/protobuf/proto" |
| 33 | ) |
| 34 | |
| 35 | func TestIntegrationWAF(t *testing.T) { |
| 36 | if os.Getenv("GO_INTEGRATION_TUNNEL") == "" { |
| 37 | t.Skip("skipping integration tests") |
| 38 | } |
| 39 | ports := []int{21970, 21971} |
| 40 | for i, port := range ports { |
| 41 | args := []string{"server", "--cert-dir", "../certs", "--data-dir", t.TempDir(), "--listen", fmt.Sprintf("127.0.0.1:%d", port), "--listen-http", fmt.Sprint(21870 + i), "--apex", serverApex, "--virtual", "1", "--auth_user", "operator", "--auth_pass", "waf-test"} |
| 42 | if i > 0 { |
| 43 | args = append(args, "--join", fmt.Sprintf("127.0.0.1:%d", ports[0])) |
| 44 | } |
| 45 | logs, _ := startIntegrationApp(t, servercmd.Generate(), args...) |
| 46 | waitIntegrationLog(t, logs, "gateway server started") |
| 47 | } |
| 48 | target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 49 | if r.URL.Path == "/request-id" { |
| 50 | w.Header().Set("X-Request-ID", "upstream-id") |
| 51 | w.WriteHeader(http.StatusEarlyHints) |
| 52 | _, _ = io.WriteString(w, r.Header.Get("X-Request-ID")) |
| 53 | return |
| 54 | } |
| 55 | if r.URL.Path == "/ws" { |
| 56 | conn, err := (&websocket.Upgrader{}).Upgrade(w, r, nil) |
| 57 | if err != nil { |
| 58 | return |
| 59 | } |
| 60 | defer conn.Close() |
| 61 | kind, body, err := conn.ReadMessage() |
| 62 | if err == nil { |
| 63 | _ = conn.WriteMessage(kind, body) |
| 64 | } |
| 65 | return |
| 66 | } |
| 67 | body, err := io.ReadAll(r.Body) |
| 68 | if err != nil { |
| 69 | http.Error(w, err.Error(), http.StatusBadRequest) |
| 70 | return |
| 71 | } |
| 72 | _, _ = w.Write(body) |
| 73 | })) |
| 74 | t.Cleanup(target.Close) |
| 75 | file := filepath.Join(t.TempDir(), "client.yaml") |
| 76 | require.NoError(t, os.WriteFile(file, []byte(fmt.Sprintf("version: 2\napex: 127.0.0.1:%d\ntunnels:\n - target: %s\n", ports[0], target.URL)), 0600)) |
| 77 | logs, _ := startIntegrationApp(t, clientcmd.Generate(), "client", "--insecure", "tunnel", "--config", file, "--server", "127.0.0.1:21972") |
| 78 | waitIntegrationLog(t, logs, "Tunnel published") |
| 79 | host := logs.FilterMessage("Tunnel published").All()[0].ContextMap()["hostname"].(string) |
| 80 | |
| 81 | newClient := func(port int, authority string, h2 bool) *http.Client { |
| 82 | cfg := &tls.Config{ServerName: authority, InsecureSkipVerify: true} |
| 83 | if h2 { |
| 84 | cfg.NextProtos = []string{"h2"} |
| 85 | } else { |
| 86 | cfg.NextProtos = []string{"http/1.1"} |
| 87 | } |
| 88 | tp := &http.Transport{ForceAttemptHTTP2: h2, TLSClientConfig: cfg, |
| 89 | DialTLSContext: func(ctx context.Context, _, _ string) (net.Conn, error) { |
| 90 | return (&tls.Dialer{Config: cfg}).DialContext(ctx, "tcp", fmt.Sprintf("127.0.0.1:%d", port)) |
| 91 | }, |
| 92 | } |
| 93 | t.Cleanup(tp.CloseIdleConnections) |
| 94 | return &http.Client{Transport: tp, Timeout: 10 * time.Second} |
| 95 | } |
| 96 | type operatorSnapshot struct { |
| 97 | Version string `json:"version"` |
| 98 | Config json.RawMessage `json:"config"` |
| 99 | Status waf.Status `json:"status"` |
| 100 | } |
| 101 | operatorClients := []*http.Client{newClient(ports[0], serverApex, true), newClient(ports[1], serverApex, true)} |
| 102 | operatorCall := func(index int, method string, value proto.Message) operatorSnapshot { |
| 103 | t.Helper() |
| 104 | var data []byte |
| 105 | if value != nil { |
| 106 | var err error |
| 107 | data, err = waf.MarshalJSON(value) |
| 108 | require.NoError(t, err) |
| 109 | } |
| 110 | req, err := http.NewRequest(method, "https://"+serverApex+"/_internal/api/config/waf", bytes.NewReader(data)) |
| 111 | require.NoError(t, err) |
| 112 | req.SetBasicAuth("operator", "waf-test") |
| 113 | req.Header.Set("Content-Type", "application/json") |
| 114 | resp, err := operatorClients[index].Do(req) |
| 115 | require.NoError(t, err) |
| 116 | defer resp.Body.Close() |
| 117 | body, err := io.ReadAll(resp.Body) |
| 118 | require.NoError(t, err) |
| 119 | require.Equal(t, http.StatusOK, resp.StatusCode, string(body)) |
| 120 | var snapshot operatorSnapshot |
| 121 | require.NoError(t, json.Unmarshal(body, &snapshot)) |
| 122 | return snapshot |
| 123 | } |
| 124 | initial := operatorCall(0, http.MethodGet, nil) |
| 125 | initialConfig := new(protocol.WAFSettings) |
| 126 | require.NoError(t, waf.DecodeJSON(bytes.NewReader(initial.Config), initialConfig)) |
| 127 | require.False(t, initialConfig.Enabled) |
| 128 | settings := waf.DefaultSettings() |
| 129 | settings.Enabled = true |
| 130 | settings.PinnedVersion = "4.25.2" // Embedded release keeps this integration independent of upstream availability. |
| 131 | saved := operatorCall(0, http.MethodPut, &protocol.SetWAFSettingsRequest{ExpectedVersion: initial.Version, Config: settings}) |
| 132 | for i := range ports { |
| 133 | require.Eventually(t, func() bool { |
| 134 | state := operatorCall(i, http.MethodGet, nil) |
| 135 | return state.Status.Ready && state.Status.Enabled && state.Status.AppliedVersion == saved.Version |
| 136 | }, 30*time.Second, time.Second, "WAF intent must replicate and activate") |
| 137 | } |
| 138 | attackPath := "/allowed?q=" + url.QueryEscape("<script>alert(1)</script>") |
| 139 | request := func(c *http.Client, path string, body string) (int, []byte, string) { |
| 140 | t.Helper() |
| 141 | method := http.MethodGet |
| 142 | if body != "" { |
| 143 | method = http.MethodPost |
| 144 | } |
| 145 | r, err := http.NewRequest(method, "https://"+host+path, strings.NewReader(body)) |
| 146 | require.NoError(t, err) |
| 147 | r.Header.Set("Accept", "application/json") |
| 148 | if body != "" { |
| 149 | r.Header.Set("Content-Type", "application/json") |
| 150 | } |
| 151 | resp, err := c.Do(r) |
| 152 | require.NoError(t, err) |
| 153 | defer resp.Body.Close() |
| 154 | data, err := io.ReadAll(resp.Body) |
| 155 | require.NoError(t, err) |
| 156 | return resp.StatusCode, data, resp.Header.Get("X-Request-ID") |
| 157 | } |
| 158 | clients := []*http.Client{newClient(ports[0], host, false), newClient(ports[1], host, true)} |
| 159 | h3 := &http3.Transport{TLSClientConfig: &tls.Config{ServerName: host, InsecureSkipVerify: true}, Dial: func(ctx context.Context, _ string, cfg *tls.Config, qc *quic.Config) (*quic.Conn, error) { |
| 160 | return quic.DialAddr(ctx, fmt.Sprintf("127.0.0.1:%d", ports[0]), cfg, qc) |
| 161 | }} |
| 162 | t.Cleanup(func() { _ = h3.Close() }) |
| 163 | clients = append(clients, &http.Client{Transport: h3, Timeout: 10 * time.Second}) |
| 164 | var denial struct { |
| 165 | RequestID string `json:"request_id"` |
| 166 | Rules []struct { |
| 167 | ID int `json:"id"` |
| 168 | Excludable bool `json:"excludable"` |
| 169 | } `json:"rules"` |
| 170 | } |
| 171 | for _, c := range clients { |
| 172 | code, data, requestID := request(c, attackPath, "") |
| 173 | require.Equal(t, http.StatusForbidden, code, string(data)) |
| 174 | require.NoError(t, json.Unmarshal(data, &denial)) |
| 175 | require.NotEmpty(t, requestID) |
| 176 | require.Equal(t, requestID, denial.RequestID) |
| 177 | } |
| 178 | missing := "missing-waf-test." + serverApex |
| 179 | missingResponse, err := newClient(ports[0], missing, false).Get("https://" + missing + attackPath) |
| 180 | require.NoError(t, err) |
| 181 | _, _ = io.Copy(io.Discard, missingResponse.Body) |
| 182 | missingResponse.Body.Close() |
| 183 | require.Equal(t, http.StatusNotFound, missingResponse.StatusCode, "missing routes must be rejected before attack inspection") |
| 184 | |
| 185 | var policyJSON json.RawMessage |
| 186 | policy := new(protocol.HostWAFResponse) |
| 187 | policyPath := "/waf?hostname=" + url.QueryEscape(strings.TrimSuffix(host, "."+serverApex)) |
| 188 | require.Equal(t, http.StatusOK, localTokenRequest(t, 21972, http.MethodGet, policyPath, nil, &policyJSON)) |
| 189 | require.NoError(t, waf.DecodeJSON(bytes.NewReader(policyJSON), policy)) |
| 190 | for _, rule := range denial.Rules { |
| 191 | if rule.Excludable { |
| 192 | policy.Policy.Exclusions = append(policy.Policy.Exclusions, &protocol.WAFExclusion{RuleId: uint32(rule.ID), Path: "/allowed"}) |
| 193 | } |
| 194 | } |
| 195 | require.NotEmpty(t, policy.Policy.Exclusions) |
| 196 | policyRequest, err := waf.MarshalJSON(&protocol.SetHostWAFRequest{ExpectedVersion: policy.Version, Policy: policy.Policy}) |
| 197 | require.NoError(t, err) |
| 198 | require.Equal(t, http.StatusOK, localTokenRequest(t, 21972, http.MethodPut, policyPath, json.RawMessage(policyRequest), &policyJSON)) |
| 199 | for _, c := range clients { |
| 200 | require.Eventually(t, func() bool { |
| 201 | code, _, _ := request(c, attackPath, "") |
| 202 | return code == http.StatusOK |
| 203 | }, 35*time.Second, time.Second, "saved hostname policy must become visible") |
| 204 | code, data, _ := request(c, strings.Replace(attackPath, "/allowed", "/other", 1), "") |
| 205 | require.Equal(t, http.StatusForbidden, code, string(data)) |
| 206 | } |
| 207 | body := `{"message":"` + strings.Repeat("a", waf.DefaultBodyLimit*2) + `"}` |
| 208 | code, received, _ := request(clients[1], "/upload", body) |
| 209 | require.Equal(t, http.StatusOK, code, string(received)) |
| 210 | require.Len(t, received, len(body), "inspection must preserve upload length") |
| 211 | require.Equal(t, body, string(received), "inspection must replay the complete upload") |
| 212 | |
| 213 | var earlyHints atomic.Bool |
| 214 | hintContext := httptrace.WithClientTrace(t.Context(), &httptrace.ClientTrace{ |
| 215 | Got1xxResponse: func(code int, _ textproto.MIMEHeader) error { |
| 216 | if code == http.StatusEarlyHints { |
| 217 | earlyHints.Store(true) |
| 218 | } |
| 219 | return nil |
| 220 | }, |
| 221 | }) |
| 222 | hintRequest, err := http.NewRequestWithContext(hintContext, http.MethodGet, "https://"+host+"/request-id", nil) |
| 223 | require.NoError(t, err) |
| 224 | hintResponse, err := clients[0].Do(hintRequest) |
| 225 | require.NoError(t, err) |
| 226 | receivedID, err := io.ReadAll(hintResponse.Body) |
| 227 | hintResponse.Body.Close() |
| 228 | require.NoError(t, err) |
| 229 | require.Equal(t, http.StatusOK, hintResponse.StatusCode) |
| 230 | require.True(t, earlyHints.Load()) |
| 231 | require.NotEmpty(t, receivedID) |
| 232 | require.Equal(t, []string{string(receivedID)}, hintResponse.Header.Values("X-Request-ID"), "final response must preserve the gateway ID after Early Hints") |
| 233 | ws, _, err := (&websocket.Dialer{TLSClientConfig: &tls.Config{ServerName: host, InsecureSkipVerify: true}, NetDialContext: func(ctx context.Context, _, _ string) (net.Conn, error) { |
| 234 | return (&net.Dialer{}).DialContext(ctx, "tcp", fmt.Sprintf("127.0.0.1:%d", ports[0])) |
| 235 | }}).DialContext(t.Context(), "wss://"+host+"/ws", nil) |
| 236 | require.NoError(t, err) |
| 237 | defer ws.Close() |
| 238 | require.NoError(t, ws.SetReadDeadline(time.Now().Add(5*time.Second))) |
| 239 | require.NoError(t, ws.WriteMessage(websocket.TextMessage, []byte("hello"))) |
| 240 | _, received, err = ws.ReadMessage() |
| 241 | require.NoError(t, err) |
| 242 | require.Equal(t, "hello", string(received)) |
| 243 | } |