httpTransformer_test.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  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. connWriteLens []int
  44. connWriteErrs []error
  45. }
  46. tests := []test{
  47. {
  48. name: "written in chunks",
  49. input: "POST / HTTP/1.1\r\nContent-Length: 4\r\n\r\nabcd",
  50. wantOutput: "POST / HTTP/1.1\r\nContent-Length: 4\r\n\r\nabcd",
  51. chunkSize: 1,
  52. },
  53. {
  54. name: "written in a single write",
  55. input: "POST / HTTP/1.1\r\nContent-Length: 4\r\n\r\nabcd",
  56. wantOutput: "POST / HTTP/1.1\r\nContent-Length: 4\r\n\r\nabcd",
  57. chunkSize: 999,
  58. },
  59. {
  60. name: "written in single write with error",
  61. input: "POST / HTTP/1.1\r\nContent-Length: 4\r\n\r\nabcd",
  62. wantOutput: "POST / HTTP/1.1\r\nContent-Length: 4\r\n\r\nabcd",
  63. chunkSize: 999,
  64. connWriteErrs: []error{errors.New("err1")},
  65. },
  66. {
  67. name: "written with partial write and errors",
  68. input: "POST / HTTP/1.1\r\nContent-Length: 4\r\n\r\nabcd",
  69. wantOutput: "POST / HTTP/1.1\r\nContent-Length: 4\r\n\r\nabcd",
  70. chunkSize: 1,
  71. connWriteLimit: 1,
  72. connWriteErrs: []error{errors.New("err1"), errors.New("err2")},
  73. },
  74. {
  75. name: "transform not applied to body",
  76. input: "POST / HTTP/1.1\r\nContent-Length: 4\r\n\r\nabcd",
  77. wantOutput: "POST / HTTP/1.1\r\nContent-Length: 4\r\n\r\nabcd",
  78. chunkSize: 1,
  79. transform: Spec{[2]string{"abcd", "efgh"}},
  80. },
  81. {
  82. name: "Content-Length missing",
  83. input: "POST / HTTP/1.1\r\n\r\nabcd",
  84. wantError: errors.New("Content-Length missing"),
  85. chunkSize: 1,
  86. },
  87. {
  88. name: "Content-Length overflow",
  89. input: fmt.Sprintf("POST / HTTP/1.1\r\nContent-Length: %d\r\n\r\nabcd", uint64(math.MaxUint64)),
  90. wantError: errors.New("strconv.ParseUint: parsing \"18446744073709551615\": value out of range"),
  91. chunkSize: 1,
  92. },
  93. {
  94. name: "incorrect Content-Length header value",
  95. input: "POST / HTTP/1.1\r\nContent-Length: 3\r\n\r\nabcd",
  96. wantOutput: "POST / HTTP/1.1\r\nContent-Length: 3\r\n\r\nabc",
  97. chunkSize: 1,
  98. },
  99. {
  100. name: "written in a single write with errors and partial writes",
  101. input: "POST / HTTP/1.1\r\nHost: example.com\r\nContent-Length: 0\r\n\r\n",
  102. wantOutput: "POST / HTTP/1.1\r\nContent-Length: 0\r\n\r\n",
  103. chunkSize: 999,
  104. transform: Spec{[2]string{"Host: example.com\r\n", ""}},
  105. connWriteErrs: []error{errors.New("err1"), nil, errors.New("err2"), nil, nil, errors.New("err3")},
  106. connWriteLens: []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10},
  107. },
  108. {
  109. name: "written in a single write with error and partial write",
  110. input: "POST / HTTP/1.1\r\nHost: example.com\r\nContent-Length: 4\r\n\r\nabcd",
  111. wantOutput: "POST / HTTP/1.1\r\nContent-Length: 4\r\n\r\nabcd",
  112. chunkSize: 999,
  113. transform: Spec{[2]string{"Host: example.com\r\n", ""}},
  114. connWriteErrs: []error{errors.New("err1")},
  115. connWriteLens: []int{28}, // write lands mid "\r\n\r\n"
  116. },
  117. {
  118. name: "transform",
  119. input: "POST / HTTP/1.1\r\nContent-Length: 4\r\n\r\nabcd",
  120. wantOutput: "POST / HTTP/1.1\r\nContent-Length: 100\r\n\r\nabcd",
  121. chunkSize: 1,
  122. transform: Spec{[2]string{"4", "100"}},
  123. },
  124. {
  125. name: "transform with partial write and errors in header write",
  126. input: "POST / HTTP/1.1\r\nContent-Length: 4\r\n\r\nabcd",
  127. wantOutput: "POST / HTTP/1.1\r\nContent-Length: 100\r\n\r\nabcd",
  128. chunkSize: 1,
  129. transform: Spec{[2]string{"4", "100"}},
  130. connWriteLimit: 1,
  131. connWriteErrs: []error{errors.New("err1"), errors.New("err2")},
  132. },
  133. {
  134. name: "transform with chunk write and errors in body write",
  135. input: "POST / HTTP/1.1\r\nContent-Length: 4\r\n\r\nabcd",
  136. wantOutput: "POST / HTTP/1.1\r\nContent-Length: 100\r\n\r\nabcd",
  137. chunkSize: 39,
  138. transform: Spec{[2]string{"4", "100"}},
  139. connWriteLimit: 1,
  140. connWriteErrs: []error{errors.New("err1"), errors.New("err2"), errors.New("err3")},
  141. },
  142. // Multiple HTTP requests written in a single write.
  143. {
  144. name: "multiple HTTP requests written in a single write",
  145. input: "POST / HTTP/1.1\r\nContent-Length: 4\r\n\r\nabcdPOST / HTTP/1.1\r\nContent-Length: 2\r\n\r\n12",
  146. wantOutput: "POST / HTTP/1.1\r\nContent-Length: 4\r\n\r\nabcdPOST / HTTP/1.1\r\nContent-Length: 2\r\n\r\n12",
  147. chunkSize: 999,
  148. },
  149. // Multiple HTTP requests written in a single write. A write will occur
  150. // where it contains both the end of the previous HTTP request and the
  151. // start of a new one.
  152. {
  153. name: "multiple HTTP requests written in chunks",
  154. input: "POST / HTTP/1.1\r\nContent-Length: 4\r\n\r\nabcdPOST / HTTP/1.1\r\nContent-Length: 2\r\n\r\n12",
  155. wantOutput: "POST / HTTP/1.1\r\nContent-Length: 4\r\n\r\nabcdPOST / HTTP/1.1\r\nContent-Length: 2\r\n\r\n12",
  156. chunkSize: 3,
  157. },
  158. // Multiple HTTP requests written in a single write with transform.
  159. {
  160. name: "multiple HTTP requests written in a single write with transform",
  161. input: "POST / HTTP/1.1\r\nContent-Length: 4\r\n\r\nabcdPOST / HTTP/1.1\r\nContent-Length: 4\r\n\r\n12POST / HTTP/1.1\r\nContent-Length: 4\r\n\r\n34",
  162. wantOutput: "POST / HTTP/1.1\r\nContent-Length: 100\r\n\r\nabcdPOST / HTTP/1.1\r\nContent-Length: 100\r\n\r\n12POST / HTTP/1.1\r\nContent-Length: 100\r\n\r\n34",
  163. chunkSize: 999,
  164. transform: Spec{[2]string{"4", "100"}},
  165. },
  166. // Multiple HTTP requests written in a single write with transform. A
  167. // write will occur where it contains both the end of the previous HTTP
  168. // request and the start of a new one.
  169. {
  170. name: "multiple HTTP requests written in chunks with transform",
  171. input: "POST / HTTP/1.1\r\nContent-Length: 4\r\n\r\nabcdPOST / HTTP/1.1\r\nContent-Length: 4\r\n\r\n12",
  172. wantOutput: "POST / HTTP/1.1\r\nContent-Length: 100\r\n\r\nabcdPOST / HTTP/1.1\r\nContent-Length: 100\r\n\r\n12",
  173. chunkSize: 4, // ensure one write contains bytes from both reqs
  174. transform: Spec{[2]string{"4", "100"}},
  175. },
  176. }
  177. for _, tt := range tests {
  178. t.Run(tt.name, func(t *testing.T) {
  179. seed, err := prng.NewSeed()
  180. if err != nil {
  181. t.Fatalf("prng.NewSeed failed %v", err)
  182. }
  183. conn := testConn{
  184. writeLimit: tt.connWriteLimit,
  185. writeLens: tt.connWriteLens,
  186. writeErrs: tt.connWriteErrs,
  187. }
  188. transformer := &HTTPTransformer{
  189. transform: tt.transform,
  190. seed: seed,
  191. Conn: &conn,
  192. }
  193. remain := []byte(tt.input)
  194. // Write input bytes to transformer in chunks and then check
  195. // output.
  196. for {
  197. if len(remain) == 0 {
  198. break
  199. }
  200. var b []byte
  201. if len(remain) < tt.chunkSize {
  202. b = remain
  203. } else {
  204. b = remain[:tt.chunkSize]
  205. }
  206. expectedErr := len(conn.writeErrs) > 0
  207. var n int
  208. n, err = transformer.Write(b)
  209. if err != nil {
  210. if expectedErr {
  211. // reset err
  212. err = nil
  213. } else {
  214. // err checked outside loop
  215. break
  216. }
  217. }
  218. remain = remain[n:]
  219. }
  220. if tt.wantError == nil {
  221. if err != nil {
  222. t.Fatalf("unexpected error %v", err)
  223. }
  224. } else {
  225. // tt.wantError != nil
  226. if err == nil {
  227. t.Fatalf("expected error %v", tt.wantError)
  228. } else if !strings.Contains(err.Error(), tt.wantError.Error()) {
  229. t.Fatalf("expected error %v got %v", tt.wantError, err)
  230. }
  231. }
  232. if tt.wantError == nil && string(conn.b) != tt.wantOutput {
  233. 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))
  234. }
  235. })
  236. }
  237. }
  238. func TestHTTPTransformerHTTPServer(t *testing.T) {
  239. type test struct {
  240. name string
  241. request func(string) *http.Request
  242. wantBody string
  243. transform Spec
  244. }
  245. tests := []test{
  246. {
  247. name: "request body truncated",
  248. transform: Spec{[2]string{"Content-Length: 4", "Content-Length: 3"}},
  249. request: func(addr string) *http.Request {
  250. body := bytes.NewReader([]byte("abcd"))
  251. req, err := http.NewRequest("POST", "http://"+addr, body)
  252. if err != nil {
  253. panic(err)
  254. }
  255. return req
  256. },
  257. wantBody: "abc",
  258. },
  259. }
  260. for _, tt := range tests {
  261. t.Run(tt.name, func(t *testing.T) {
  262. seed, err := prng.NewSeed()
  263. if err != nil {
  264. t.Fatalf("prng.NewSeed failed %v", err)
  265. }
  266. params := &HTTPTransformerParameters{
  267. ProtocolTransformName: "spec",
  268. ProtocolTransformSpec: tt.transform,
  269. ProtocolTransformSeed: seed,
  270. }
  271. dialer := func(ctx context.Context, network, address string) (net.Conn, error) {
  272. return net.Dial(network, address)
  273. }
  274. httpTransport := &http.Transport{
  275. DialContext: WrapDialerWithHTTPTransformer(dialer, params),
  276. }
  277. type serverRequest struct {
  278. req *http.Request
  279. body []byte
  280. }
  281. serverReq := make(chan *serverRequest, 1)
  282. http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
  283. b, err := io.ReadAll(r.Body)
  284. if err != nil {
  285. w.WriteHeader(http.StatusInternalServerError)
  286. }
  287. go func() {
  288. serverReq <- &serverRequest{
  289. req: r,
  290. body: b,
  291. }
  292. close(serverReq)
  293. }()
  294. })
  295. s := &http.Server{
  296. Addr: "127.0.0.1:8080",
  297. }
  298. go func() {
  299. s.ListenAndServe()
  300. }()
  301. client := http.Client{
  302. Transport: httpTransport,
  303. Timeout: 2 * time.Second,
  304. }
  305. req := tt.request(s.Addr)
  306. resp, err := client.Do(req)
  307. // first shutdown server, then check err
  308. shutdownErr := s.Shutdown(context.Background())
  309. if shutdownErr != nil {
  310. t.Fatalf("s.Shutdown failed %v", shutdownErr)
  311. }
  312. if err != nil {
  313. t.Fatalf("client.Do failed %v", err)
  314. }
  315. if resp.StatusCode != http.StatusOK {
  316. t.Fatalf("expected 200 but got %d", resp.StatusCode)
  317. }
  318. r := <-serverReq
  319. if tt.wantBody != string(r.body) {
  320. t.Fatalf("expected body %s but got %s", tt.wantBody, string(r.body))
  321. }
  322. })
  323. }
  324. }
  325. func escapeNewlines(s string) string {
  326. s = strings.ReplaceAll(s, "\n", "\\n")
  327. s = strings.ReplaceAll(s, "\r", "\\r")
  328. return s
  329. }
  330. type testConn struct {
  331. // b is the accumulated bytes from Write() calls.
  332. b []byte
  333. // writeLimit is the max number of bytes that will be written in a Write()
  334. // call.
  335. writeLimit int
  336. // writeLens are returned from Write() calls in order and determine the
  337. // max number of bytes that will be written. Overrides writeLimit if
  338. // non-empty. If empty, then the value of writeLimit is returned.
  339. writeLens []int
  340. // writeErrs are returned from Write() calls in order. If empty, then a nil
  341. // error is returned.
  342. writeErrs []error
  343. }
  344. func (c *testConn) Read(b []byte) (n int, err error) {
  345. return 0, nil
  346. }
  347. func (c *testConn) Write(b []byte) (n int, err error) {
  348. if len(c.writeErrs) > 0 {
  349. err = c.writeErrs[0]
  350. c.writeErrs = c.writeErrs[1:]
  351. }
  352. if len(c.writeLens) > 0 {
  353. n = c.writeLens[0]
  354. c.writeLens = c.writeLens[1:]
  355. if len(b) <= n {
  356. c.b = append(c.b, b...)
  357. n = len(b)
  358. } else {
  359. c.b = append(c.b, b[:n]...)
  360. }
  361. } else if c.writeLimit != 0 && c.writeLimit < len(b) {
  362. c.b = append(c.b, b[:c.writeLimit]...)
  363. n = c.writeLimit
  364. } else {
  365. c.b = append(c.b, b...)
  366. n = len(b)
  367. }
  368. return
  369. }
  370. func (c *testConn) Close() error {
  371. return nil
  372. }
  373. func (c *testConn) LocalAddr() net.Addr {
  374. return nil
  375. }
  376. func (c *testConn) RemoteAddr() net.Addr {
  377. return nil
  378. }
  379. func (c *testConn) SetDeadline(t time.Time) error {
  380. return nil
  381. }
  382. func (c *testConn) SetReadDeadline(t time.Time) error {
  383. return nil
  384. }
  385. func (c *testConn) SetWriteDeadline(t time.Time) error {
  386. return nil
  387. }