httpTransformer_test.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. /*
  2. * Copyright (c) 2023, Psiphon Inc.
  3. * All rights reserved.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. */
  19. package transforms
  20. import (
  21. "bytes"
  22. "context"
  23. "errors"
  24. "fmt"
  25. "io"
  26. "math"
  27. "net"
  28. "net/http"
  29. "strings"
  30. "testing"
  31. "time"
  32. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/prng"
  33. )
  34. func TestHTTPTransformerHTTPRequest(t *testing.T) {
  35. type test struct {
  36. name string
  37. input string
  38. wantOutput string
  39. wantError error
  40. chunkSize int
  41. transform Spec
  42. connWriteLimit int
  43. connWriteErrs []error
  44. }
  45. tests := []test{
  46. {
  47. name: "no transform",
  48. input: "HTTP 1.1\r\nContent-Length: 4\r\n\r\nabcd",
  49. wantOutput: "HTTP 1.1\r\nContent-Length: 4\r\n\r\nabcd",
  50. chunkSize: 1,
  51. },
  52. {
  53. name: "no transform with partial write and errors",
  54. input: "HTTP 1.1\r\nContent-Length: 4\r\n\r\nabcd",
  55. wantOutput: "HTTP 1.1\r\nContent-Length: 4\r\n\r\nabcd",
  56. chunkSize: 1,
  57. connWriteLimit: 1,
  58. connWriteErrs: []error{errors.New("err1"), errors.New("err2")},
  59. },
  60. {
  61. name: "transform not applied to body",
  62. input: "HTTP 1.1\r\nContent-Length: 4\r\n\r\nabcd",
  63. wantOutput: "HTTP 1.1\r\nContent-Length: 4\r\n\r\nabcd",
  64. chunkSize: 1,
  65. transform: Spec{[2]string{"abcd", "efgh"}},
  66. },
  67. {
  68. name: "Content-Length missing",
  69. input: "HTTP 1.1\r\n\r\nabcd",
  70. wantError: errors.New("Content-Length missing"),
  71. chunkSize: 1,
  72. },
  73. {
  74. name: "Content-Length overflow",
  75. input: fmt.Sprintf("HTTP 1.1\r\nContent-Length: %d\r\n\r\nabcd", uint64(math.MaxUint64)),
  76. wantError: errors.New("strconv.ParseUint: parsing \"18446744073709551615\": value out of range"),
  77. chunkSize: 1,
  78. },
  79. {
  80. name: "no transform",
  81. input: "HTTP 1.1\r\nContent-Length: 4\r\n\r\nabcd",
  82. wantOutput: "HTTP 1.1\r\nContent-Length: 4\r\n\r\nabcd",
  83. chunkSize: 1,
  84. },
  85. {
  86. name: "incorrect Content-Length header value",
  87. input: "HTTP 1.1\r\nContent-Length: 3\r\n\r\nabcd",
  88. wantOutput: "HTTP 1.1\r\nContent-Length: 3\r\n\r\nabc",
  89. chunkSize: 1,
  90. },
  91. {
  92. name: "single HTTP request written in a single write",
  93. input: "HTTP 1.1\r\nContent-Length: 4\r\n\r\nabcd",
  94. wantOutput: "HTTP 1.1\r\nContent-Length: 4\r\n\r\nabcd",
  95. chunkSize: 999,
  96. },
  97. {
  98. name: "transform",
  99. input: "POST / HTTP/1.1\r\nContent-Length: 4\r\n\r\nabcd",
  100. wantOutput: "POST / HTTP/1.1\r\nContent-Length: 100\r\n\r\nabcd",
  101. chunkSize: 1,
  102. transform: Spec{[2]string{"4", "100"}},
  103. },
  104. {
  105. name: "transform with partial write and errors in header write",
  106. input: "POST / HTTP/1.1\r\nContent-Length: 4\r\n\r\nabcd",
  107. wantOutput: "POST / HTTP/1.1\r\nContent-Length: 100\r\n\r\nabcd",
  108. chunkSize: 1,
  109. transform: Spec{[2]string{"4", "100"}},
  110. connWriteLimit: 1,
  111. connWriteErrs: []error{errors.New("err1"), errors.New("err2")},
  112. },
  113. {
  114. name: "transform with chunk write and errors in body write",
  115. input: "POST / HTTP/1.1\r\nContent-Length: 4\r\n\r\nabcd",
  116. wantOutput: "POST / HTTP/1.1\r\nContent-Length: 100\r\n\r\nabcd",
  117. chunkSize: 39,
  118. transform: Spec{[2]string{"4", "100"}},
  119. connWriteLimit: 1,
  120. connWriteErrs: []error{errors.New("err1"), errors.New("err2"), errors.New("err3")},
  121. },
  122. // Multiple HTTP requests written in a single write not supported so an
  123. // error is expected.
  124. {
  125. name: "multiple HTTP requests written in a single write",
  126. input: "HTTP 1.1\r\nContent-Length: 4\r\n\r\nabcdHTTP 1.1\r\nContent-Length: 2\r\n\r\n12",
  127. wantOutput: "HTTP 1.1\r\nContent-Length: 4\r\n\r\nabcdHTTP 1.1\r\nContent-Length: 2\r\n\r\n12",
  128. chunkSize: 999,
  129. wantError: errors.New("t.remain - uint64(n) underflows"),
  130. },
  131. // Multiple HTTP requests written in a single write not supported so an
  132. // error is expected because a write will occur where it contains both
  133. // the end of the previous HTTP request and the start of a new one.
  134. {
  135. name: "multiple HTTP requests written in chunks",
  136. input: "HTTP 1.1\r\nContent-Length: 4\r\n\r\nabcdHTTP 1.1\r\nContent-Length: 2\r\n\r\n12",
  137. wantOutput: "HTTP 1.1\r\nContent-Length: 4\r\n\r\nabcdHTTP 1.1\r\nContent-Length: 2\r\n\r\n12",
  138. chunkSize: 3,
  139. wantError: errors.New("t.remain - uint64(n) underflows"),
  140. },
  141. }
  142. for _, tt := range tests {
  143. t.Run(tt.name, func(t *testing.T) {
  144. seed, err := prng.NewSeed()
  145. if err != nil {
  146. t.Fatalf("prng.NewSeed failed %v", err)
  147. }
  148. conn := testConn{
  149. writeLimit: tt.connWriteLimit,
  150. writeErrs: tt.connWriteErrs,
  151. }
  152. transformer := &HTTPTransformer{
  153. transform: tt.transform,
  154. seed: seed,
  155. Conn: &conn,
  156. }
  157. remain := []byte(tt.input)
  158. // Write input bytes to transformer in chunks and then check
  159. // output.
  160. for {
  161. if len(remain) == 0 {
  162. break
  163. }
  164. var b []byte
  165. if len(remain) < tt.chunkSize {
  166. b = remain
  167. } else {
  168. b = remain[:tt.chunkSize]
  169. }
  170. expectedErr := len(conn.writeErrs) > 0
  171. var n int
  172. n, err = transformer.Write(b)
  173. if err != nil {
  174. if expectedErr {
  175. // reset err
  176. err = nil
  177. } else {
  178. // err checked outside loop
  179. break
  180. }
  181. }
  182. remain = remain[n:]
  183. }
  184. if tt.wantError == nil {
  185. if err != nil {
  186. t.Fatalf("unexpected error %v", err)
  187. }
  188. } else {
  189. // tt.wantError != nil
  190. if err == nil {
  191. t.Fatalf("expected error %v", tt.wantError)
  192. } else if !strings.Contains(err.Error(), tt.wantError.Error()) {
  193. t.Fatalf("expected error %v got %v", tt.wantError, err)
  194. }
  195. }
  196. if tt.wantError == nil && string(conn.b) != tt.wantOutput {
  197. t.Fatalf("expected \"%s\" of len %d but got \"%s\" of len %d", escapeNewlines(tt.wantOutput), len(tt.wantOutput), escapeNewlines(string(conn.b)), len(conn.b))
  198. }
  199. })
  200. }
  201. }
  202. func TestHTTPTransformerHTTPServer(t *testing.T) {
  203. type test struct {
  204. name string
  205. request func(string) *http.Request
  206. wantBody string
  207. transform Spec
  208. }
  209. tests := []test{
  210. {
  211. name: "request body truncated",
  212. transform: Spec{[2]string{"Content-Length: 4", "Content-Length: 3"}},
  213. request: func(addr string) *http.Request {
  214. body := bytes.NewReader([]byte("abcd"))
  215. req, err := http.NewRequest("POST", "http://"+addr, body)
  216. if err != nil {
  217. panic(err)
  218. }
  219. return req
  220. },
  221. wantBody: "abc",
  222. },
  223. }
  224. for _, tt := range tests {
  225. t.Run(tt.name, func(t *testing.T) {
  226. seed, err := prng.NewSeed()
  227. if err != nil {
  228. t.Fatalf("prng.NewSeed failed %v", err)
  229. }
  230. params := &HTTPTransformerParameters{
  231. ProtocolTransformName: "spec",
  232. ProtocolTransformSpec: tt.transform,
  233. ProtocolTransformSeed: seed,
  234. }
  235. dialer := func(ctx context.Context, network, address string) (net.Conn, error) {
  236. return net.Dial(network, address)
  237. }
  238. httpTransport := &http.Transport{
  239. DialContext: WrapDialerWithHTTPTransformer(dialer, params),
  240. }
  241. type serverRequest struct {
  242. req *http.Request
  243. body []byte
  244. }
  245. serverReq := make(chan *serverRequest, 1)
  246. http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
  247. b, err := io.ReadAll(r.Body)
  248. if err != nil {
  249. w.WriteHeader(http.StatusInternalServerError)
  250. }
  251. go func() {
  252. serverReq <- &serverRequest{
  253. req: r,
  254. body: b,
  255. }
  256. close(serverReq)
  257. }()
  258. })
  259. s := &http.Server{
  260. Addr: "127.0.0.1:8080",
  261. }
  262. go func() {
  263. s.ListenAndServe()
  264. }()
  265. client := http.Client{
  266. Transport: httpTransport,
  267. Timeout: 2 * time.Second,
  268. }
  269. req := tt.request(s.Addr)
  270. resp, err := client.Do(req)
  271. // first shutdown server, then check err
  272. shutdownErr := s.Shutdown(context.Background())
  273. if shutdownErr != nil {
  274. t.Fatalf("s.Shutdown failed %v", shutdownErr)
  275. }
  276. if err != nil {
  277. t.Fatalf("client.Do failed %v", err)
  278. }
  279. if resp.StatusCode != http.StatusOK {
  280. t.Fatalf("expected 200 but got %d", resp.StatusCode)
  281. }
  282. r := <-serverReq
  283. if tt.wantBody != string(r.body) {
  284. t.Fatalf("expected body %s but got %s", tt.wantBody, string(r.body))
  285. }
  286. })
  287. }
  288. }
  289. func escapeNewlines(s string) string {
  290. s = strings.ReplaceAll(s, "\n", "\\n")
  291. s = strings.ReplaceAll(s, "\r", "\\r")
  292. return s
  293. }
  294. type testConn struct {
  295. // b is the accumulated bytes from Write() calls.
  296. b []byte
  297. // writeLimit is the max number of bytes that will be written in a Write()
  298. // call.
  299. writeLimit int
  300. // writeErrs are returned from Write() calls in order. If empty, then a nil
  301. // error is returned.
  302. writeErrs []error
  303. }
  304. func (c *testConn) Read(b []byte) (n int, err error) {
  305. return 0, nil
  306. }
  307. func (c *testConn) Write(b []byte) (n int, err error) {
  308. if len(c.writeErrs) > 0 {
  309. err = c.writeErrs[0]
  310. c.writeErrs = c.writeErrs[1:]
  311. }
  312. if c.writeLimit != 0 && c.writeLimit < len(b) {
  313. c.b = append(c.b, b[:c.writeLimit]...)
  314. n = c.writeLimit
  315. return
  316. }
  317. c.b = append(c.b, b...)
  318. n = len(b)
  319. return
  320. }
  321. func (c *testConn) Close() error {
  322. return nil
  323. }
  324. func (c *testConn) LocalAddr() net.Addr {
  325. return nil
  326. }
  327. func (c *testConn) RemoteAddr() net.Addr {
  328. return nil
  329. }
  330. func (c *testConn) SetDeadline(t time.Time) error {
  331. return nil
  332. }
  333. func (c *testConn) SetReadDeadline(t time.Time) error {
  334. return nil
  335. }
  336. func (c *testConn) SetWriteDeadline(t time.Time) error {
  337. return nil
  338. }