frankenphp_test.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814
  1. // In all tests, headers added to requests are copied on the heap using strings.Clone.
  2. // This was originally a workaround for https://github.com/golang/go/issues/65286#issuecomment-1920087884 (fixed in Go 1.22),
  3. // but this allows to catch panics occuring in real life but not when the string is in the internal binary memory.
  4. package frankenphp_test
  5. import (
  6. "context"
  7. "fmt"
  8. "io"
  9. "log"
  10. "net/http"
  11. "net/http/cookiejar"
  12. "net/http/httptest"
  13. "net/http/httptrace"
  14. "net/textproto"
  15. "net/url"
  16. "os"
  17. "os/exec"
  18. "strconv"
  19. "strings"
  20. "sync"
  21. "testing"
  22. "github.com/dunglas/frankenphp"
  23. "github.com/stretchr/testify/assert"
  24. "github.com/stretchr/testify/require"
  25. "go.uber.org/zap"
  26. "go.uber.org/zap/zaptest"
  27. "go.uber.org/zap/zaptest/observer"
  28. )
  29. type testOptions struct {
  30. workerScript string
  31. nbWorkers int
  32. env map[string]string
  33. nbParrallelRequests int
  34. realServer bool
  35. logger *zap.Logger
  36. initOpts []frankenphp.Option
  37. }
  38. func runTest(t *testing.T, test func(func(http.ResponseWriter, *http.Request), *httptest.Server, int), opts *testOptions) {
  39. if opts == nil {
  40. opts = &testOptions{}
  41. }
  42. if opts.nbParrallelRequests == 0 {
  43. opts.nbParrallelRequests = 100
  44. }
  45. cwd, _ := os.Getwd()
  46. testDataDir := cwd + "/testdata/"
  47. if opts.logger == nil {
  48. opts.logger = zaptest.NewLogger(t)
  49. }
  50. initOpts := []frankenphp.Option{frankenphp.WithLogger(opts.logger)}
  51. if opts.workerScript != "" {
  52. initOpts = append(initOpts, frankenphp.WithWorkers(testDataDir+opts.workerScript, opts.nbWorkers, opts.env))
  53. }
  54. initOpts = append(initOpts, opts.initOpts...)
  55. err := frankenphp.Init(initOpts...)
  56. require.Nil(t, err)
  57. defer frankenphp.Shutdown()
  58. handler := func(w http.ResponseWriter, r *http.Request) {
  59. req, err := frankenphp.NewRequestWithContext(r, frankenphp.WithRequestDocumentRoot(testDataDir, false))
  60. assert.NoError(t, err)
  61. err = frankenphp.ServeHTTP(w, req)
  62. assert.NoError(t, err)
  63. }
  64. var ts *httptest.Server
  65. if opts.realServer {
  66. ts = httptest.NewServer(http.HandlerFunc(handler))
  67. defer ts.Close()
  68. }
  69. var wg sync.WaitGroup
  70. wg.Add(opts.nbParrallelRequests)
  71. for i := 0; i < opts.nbParrallelRequests; i++ {
  72. go func(i int) {
  73. test(handler, ts, i)
  74. wg.Done()
  75. }(i)
  76. }
  77. wg.Wait()
  78. }
  79. func TestHelloWorld_module(t *testing.T) { testHelloWorld(t, nil) }
  80. func TestHelloWorld_worker(t *testing.T) {
  81. testHelloWorld(t, &testOptions{workerScript: "index.php"})
  82. }
  83. func testHelloWorld(t *testing.T, opts *testOptions) {
  84. runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) {
  85. req := httptest.NewRequest("GET", fmt.Sprintf("http://example.com/index.php?i=%d", i), nil)
  86. w := httptest.NewRecorder()
  87. handler(w, req)
  88. resp := w.Result()
  89. body, _ := io.ReadAll(resp.Body)
  90. assert.Equal(t, fmt.Sprintf("I am by birth a Genevese (%d)", i), string(body))
  91. }, opts)
  92. }
  93. func TestFinishRequest_module(t *testing.T) { testFinishRequest(t, nil) }
  94. func TestFinishRequest_worker(t *testing.T) {
  95. testFinishRequest(t, &testOptions{workerScript: "finish-request.php"})
  96. }
  97. func testFinishRequest(t *testing.T, opts *testOptions) {
  98. runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) {
  99. req := httptest.NewRequest("GET", fmt.Sprintf("http://example.com/finish-request.php?i=%d", i), nil)
  100. w := httptest.NewRecorder()
  101. handler(w, req)
  102. resp := w.Result()
  103. body, _ := io.ReadAll(resp.Body)
  104. assert.Equal(t, fmt.Sprintf("This is output %d\n", i), string(body))
  105. }, opts)
  106. }
  107. func TestServerVariable_module(t *testing.T) {
  108. testServerVariable(t, nil)
  109. }
  110. func TestServerVariable_worker(t *testing.T) {
  111. testServerVariable(t, &testOptions{workerScript: "server-variable.php"})
  112. }
  113. func testServerVariable(t *testing.T, opts *testOptions) {
  114. runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) {
  115. req := httptest.NewRequest("POST", fmt.Sprintf("http://example.com/server-variable.php/baz/bat?foo=a&bar=b&i=%d#hash", i), strings.NewReader("foo"))
  116. req.SetBasicAuth(strings.Clone("kevin"), strings.Clone("password"))
  117. req.Header.Add(strings.Clone("Content-Type"), strings.Clone("text/plain"))
  118. w := httptest.NewRecorder()
  119. handler(w, req)
  120. resp := w.Result()
  121. body, _ := io.ReadAll(resp.Body)
  122. strBody := string(body)
  123. assert.Contains(t, strBody, "[REMOTE_HOST]")
  124. assert.Contains(t, strBody, "[REMOTE_USER] => kevin")
  125. assert.Contains(t, strBody, "[PHP_AUTH_USER] => kevin")
  126. assert.Contains(t, strBody, "[PHP_AUTH_PW] => password")
  127. assert.Contains(t, strBody, "[HTTP_AUTHORIZATION] => Basic a2V2aW46cGFzc3dvcmQ=")
  128. assert.Contains(t, strBody, "[DOCUMENT_ROOT]")
  129. assert.Contains(t, strBody, "[PHP_SELF] => /server-variable.php/baz/bat")
  130. assert.Contains(t, strBody, "[CONTENT_TYPE] => text/plain")
  131. assert.Contains(t, strBody, fmt.Sprintf("[QUERY_STRING] => foo=a&bar=b&i=%d#hash", i))
  132. assert.Contains(t, strBody, fmt.Sprintf("[REQUEST_URI] => /server-variable.php/baz/bat?foo=a&bar=b&i=%d#hash", i))
  133. assert.Contains(t, strBody, "[CONTENT_LENGTH]")
  134. assert.Contains(t, strBody, "[REMOTE_ADDR]")
  135. assert.Contains(t, strBody, "[REMOTE_PORT]")
  136. assert.Contains(t, strBody, "[REQUEST_SCHEME] => http")
  137. assert.Contains(t, strBody, "[DOCUMENT_URI]")
  138. assert.Contains(t, strBody, "[AUTH_TYPE]")
  139. assert.Contains(t, strBody, "[REMOTE_IDENT]")
  140. assert.Contains(t, strBody, "[REQUEST_METHOD] => POST")
  141. assert.Contains(t, strBody, "[SERVER_NAME] => example.com")
  142. assert.Contains(t, strBody, "[SERVER_PROTOCOL] => HTTP/1.1")
  143. assert.Contains(t, strBody, "[SCRIPT_FILENAME]")
  144. assert.Contains(t, strBody, "[SERVER_SOFTWARE] => FrankenPHP")
  145. assert.Contains(t, strBody, "[REQUEST_TIME_FLOAT]")
  146. assert.Contains(t, strBody, "[REQUEST_TIME]")
  147. assert.Contains(t, strBody, "[SERVER_PORT] => 80")
  148. }, opts)
  149. }
  150. func TestPathInfo_module(t *testing.T) { testPathInfo(t, nil) }
  151. func TestPathInfo_worker(t *testing.T) {
  152. testPathInfo(t, &testOptions{workerScript: "server-variable.php"})
  153. }
  154. func testPathInfo(t *testing.T, opts *testOptions) {
  155. cwd, _ := os.Getwd()
  156. testDataDir := cwd + strings.Clone("/testdata/")
  157. path := strings.Clone("/server-variable.php/pathinfo")
  158. runTest(t, func(_ func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) {
  159. handler := func(w http.ResponseWriter, r *http.Request) {
  160. requestURI := r.URL.RequestURI()
  161. r.URL.Path = path
  162. rewriteRequest, err := frankenphp.NewRequestWithContext(r,
  163. frankenphp.WithRequestDocumentRoot(testDataDir, false),
  164. frankenphp.WithRequestEnv(map[string]string{"REQUEST_URI": requestURI}),
  165. )
  166. assert.NoError(t, err)
  167. err = frankenphp.ServeHTTP(w, rewriteRequest)
  168. assert.NoError(t, err)
  169. }
  170. req := httptest.NewRequest("GET", fmt.Sprintf("http://example.com/pathinfo/%d", i), nil)
  171. w := httptest.NewRecorder()
  172. handler(w, req)
  173. resp := w.Result()
  174. body, _ := io.ReadAll(resp.Body)
  175. strBody := string(body)
  176. assert.Contains(t, strBody, "[PATH_INFO] => /pathinfo")
  177. assert.Contains(t, strBody, fmt.Sprintf("[REQUEST_URI] => /pathinfo/%d", i))
  178. assert.Contains(t, strBody, "[PATH_TRANSLATED] =>")
  179. assert.Contains(t, strBody, "[SCRIPT_NAME] => /server-variable.php")
  180. }, opts)
  181. }
  182. func TestHeaders_module(t *testing.T) { testHeaders(t, nil) }
  183. func TestHeaders_worker(t *testing.T) { testHeaders(t, &testOptions{workerScript: "headers.php"}) }
  184. func testHeaders(t *testing.T, opts *testOptions) {
  185. runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) {
  186. req := httptest.NewRequest("GET", fmt.Sprintf("http://example.com/headers.php?i=%d", i), nil)
  187. w := httptest.NewRecorder()
  188. handler(w, req)
  189. resp := w.Result()
  190. body, _ := io.ReadAll(resp.Body)
  191. assert.Equal(t, "Hello", string(body))
  192. assert.Equal(t, 201, resp.StatusCode)
  193. assert.Equal(t, "bar", resp.Header.Get("Foo"))
  194. assert.Equal(t, "bar2", resp.Header.Get("Foo2"))
  195. assert.Empty(t, resp.Header.Get("Invalid"))
  196. assert.Equal(t, fmt.Sprintf("%d", i), resp.Header.Get("I"))
  197. }, opts)
  198. }
  199. func TestResponseHeaders_module(t *testing.T) { testResponseHeaders(t, nil) }
  200. func TestResponseHeaders_worker(t *testing.T) {
  201. testResponseHeaders(t, &testOptions{workerScript: "response-headers.php"})
  202. }
  203. func testResponseHeaders(t *testing.T, opts *testOptions) {
  204. runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) {
  205. req := httptest.NewRequest("GET", fmt.Sprintf("http://example.com/response-headers.php?i=%d", i), nil)
  206. w := httptest.NewRecorder()
  207. handler(w, req)
  208. resp := w.Result()
  209. body, _ := io.ReadAll(resp.Body)
  210. assert.Contains(t, string(body), "'X-Powered-By' => 'PH")
  211. assert.Contains(t, string(body), "'Foo' => 'bar',")
  212. assert.Contains(t, string(body), "'Foo2' => 'bar2',")
  213. assert.Contains(t, string(body), fmt.Sprintf("'I' => '%d',", i))
  214. assert.NotContains(t, string(body), "Invalid")
  215. }, opts)
  216. }
  217. func TestInput_module(t *testing.T) { testInput(t, nil) }
  218. func TestInput_worker(t *testing.T) { testInput(t, &testOptions{workerScript: "input.php"}) }
  219. func testInput(t *testing.T, opts *testOptions) {
  220. runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) {
  221. req := httptest.NewRequest("POST", "http://example.com/input.php", strings.NewReader(fmt.Sprintf("post data %d", i)))
  222. w := httptest.NewRecorder()
  223. handler(w, req)
  224. resp := w.Result()
  225. body, _ := io.ReadAll(resp.Body)
  226. assert.Equal(t, fmt.Sprintf("post data %d", i), string(body))
  227. assert.Equal(t, "bar", resp.Header.Get("Foo"))
  228. }, opts)
  229. }
  230. func TestPostSuperGlobals_module(t *testing.T) { testPostSuperGlobals(t, nil) }
  231. func TestPostSuperGlobals_worker(t *testing.T) {
  232. testPostSuperGlobals(t, &testOptions{workerScript: "super-globals.php"})
  233. }
  234. func testPostSuperGlobals(t *testing.T, opts *testOptions) {
  235. runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) {
  236. formData := url.Values{"baz": {"bat"}, "i": {fmt.Sprintf("%d", i)}}
  237. req := httptest.NewRequest("POST", fmt.Sprintf("http://example.com/super-globals.php?foo=bar&iG=%d", i), strings.NewReader(formData.Encode()))
  238. req.Header.Set("Content-Type", strings.Clone("application/x-www-form-urlencoded"))
  239. w := httptest.NewRecorder()
  240. handler(w, req)
  241. resp := w.Result()
  242. body, _ := io.ReadAll(resp.Body)
  243. assert.Contains(t, string(body), "'foo' => 'bar'")
  244. assert.Contains(t, string(body), fmt.Sprintf("'i' => '%d'", i))
  245. assert.Contains(t, string(body), "'baz' => 'bat'")
  246. assert.Contains(t, string(body), fmt.Sprintf("'iG' => '%d'", i))
  247. }, opts)
  248. }
  249. func TestCookies_module(t *testing.T) { testCookies(t, nil) }
  250. func TestCookies_worker(t *testing.T) { testCookies(t, &testOptions{workerScript: "cookies.php"}) }
  251. func testCookies(t *testing.T, opts *testOptions) {
  252. runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) {
  253. req := httptest.NewRequest("GET", "http://example.com/cookies.php", nil)
  254. req.AddCookie(&http.Cookie{Name: "foo", Value: "bar"})
  255. req.AddCookie(&http.Cookie{Name: "i", Value: fmt.Sprintf("%d", i)})
  256. w := httptest.NewRecorder()
  257. handler(w, req)
  258. resp := w.Result()
  259. body, _ := io.ReadAll(resp.Body)
  260. assert.Contains(t, string(body), "'foo' => 'bar'")
  261. assert.Contains(t, string(body), fmt.Sprintf("'i' => '%d'", i))
  262. }, opts)
  263. }
  264. func TestSession_module(t *testing.T) { testSession(t, nil) }
  265. func TestSession_worker(t *testing.T) {
  266. testSession(t, &testOptions{workerScript: "session.php"})
  267. }
  268. func testSession(t *testing.T, opts *testOptions) {
  269. if opts == nil {
  270. opts = &testOptions{}
  271. }
  272. opts.realServer = true
  273. runTest(t, func(_ func(http.ResponseWriter, *http.Request), ts *httptest.Server, i int) {
  274. jar, err := cookiejar.New(&cookiejar.Options{})
  275. assert.NoError(t, err)
  276. client := &http.Client{Jar: jar}
  277. resp1, err := client.Get(ts.URL + "/session.php")
  278. assert.NoError(t, err)
  279. body1, _ := io.ReadAll(resp1.Body)
  280. assert.Equal(t, "Count: 0\n", string(body1))
  281. resp2, err := client.Get(ts.URL + "/session.php")
  282. assert.NoError(t, err)
  283. body2, _ := io.ReadAll(resp2.Body)
  284. assert.Equal(t, "Count: 1\n", string(body2))
  285. }, opts)
  286. }
  287. func TestPhpInfo_module(t *testing.T) { testPhpInfo(t, nil) }
  288. func TestPhpInfo_worker(t *testing.T) { testPhpInfo(t, &testOptions{workerScript: "phpinfo.php"}) }
  289. func testPhpInfo(t *testing.T, opts *testOptions) {
  290. var logOnce sync.Once
  291. runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) {
  292. req := httptest.NewRequest("GET", fmt.Sprintf("http://example.com/phpinfo.php?i=%d", i), nil)
  293. w := httptest.NewRecorder()
  294. handler(w, req)
  295. resp := w.Result()
  296. body, _ := io.ReadAll(resp.Body)
  297. logOnce.Do(func() {
  298. t.Log(string(body))
  299. })
  300. assert.Contains(t, string(body), "frankenphp")
  301. assert.Contains(t, string(body), fmt.Sprintf("i=%d", i))
  302. }, opts)
  303. }
  304. func TestPersistentObject_module(t *testing.T) { testPersistentObject(t, nil) }
  305. func TestPersistentObject_worker(t *testing.T) {
  306. testPersistentObject(t, &testOptions{workerScript: "persistent-object.php"})
  307. }
  308. func testPersistentObject(t *testing.T, opts *testOptions) {
  309. runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) {
  310. req := httptest.NewRequest("GET", fmt.Sprintf("http://example.com/persistent-object.php?i=%d", i), nil)
  311. w := httptest.NewRecorder()
  312. handler(w, req)
  313. resp := w.Result()
  314. body, _ := io.ReadAll(resp.Body)
  315. assert.Equal(t, fmt.Sprintf(`request: %d
  316. class exists: 1
  317. id: obj1
  318. object id: 1`, i), string(body))
  319. }, opts)
  320. }
  321. func TestAutoloader_module(t *testing.T) { testAutoloader(t, nil) }
  322. func TestAutoloader_worker(t *testing.T) {
  323. testAutoloader(t, &testOptions{workerScript: "autoloader.php"})
  324. }
  325. func testAutoloader(t *testing.T, opts *testOptions) {
  326. runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) {
  327. req := httptest.NewRequest("GET", fmt.Sprintf("http://example.com/autoloader.php?i=%d", i), nil)
  328. w := httptest.NewRecorder()
  329. handler(w, req)
  330. resp := w.Result()
  331. body, _ := io.ReadAll(resp.Body)
  332. assert.Equal(t, fmt.Sprintf(`request %d
  333. my_autoloader`, i), string(body))
  334. }, opts)
  335. }
  336. func TestLog_module(t *testing.T) { testLog(t, &testOptions{}) }
  337. func TestLog_worker(t *testing.T) {
  338. testLog(t, &testOptions{workerScript: "log.php"})
  339. }
  340. func testLog(t *testing.T, opts *testOptions) {
  341. logger, logs := observer.New(zap.InfoLevel)
  342. opts.logger = zap.New(logger)
  343. runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) {
  344. req := httptest.NewRequest("GET", fmt.Sprintf("http://example.com/log.php?i=%d", i), nil)
  345. w := httptest.NewRecorder()
  346. handler(w, req)
  347. for logs.FilterMessage(fmt.Sprintf("request %d", i)).Len() <= 0 {
  348. }
  349. }, opts)
  350. }
  351. func TestConnectionAbort_module(t *testing.T) { testConnectionAbort(t, &testOptions{}) }
  352. func TestConnectionAbort_worker(t *testing.T) {
  353. testConnectionAbort(t, &testOptions{workerScript: "connectionStatusLog.php"})
  354. }
  355. func testConnectionAbort(t *testing.T, opts *testOptions) {
  356. testFinish := func(finish string) {
  357. t.Run(fmt.Sprintf("finish=%s", finish), func(t *testing.T) {
  358. logger, logs := observer.New(zap.InfoLevel)
  359. opts.logger = zap.New(logger)
  360. runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) {
  361. req := httptest.NewRequest("GET", fmt.Sprintf("http://example.com/connectionStatusLog.php?i=%d&finish=%s", i, finish), nil)
  362. w := httptest.NewRecorder()
  363. ctx, cancel := context.WithCancel(req.Context())
  364. req = req.WithContext(ctx)
  365. cancel()
  366. handler(w, req)
  367. for logs.FilterMessage(fmt.Sprintf("request %d: 1", i)).Len() <= 0 {
  368. }
  369. }, opts)
  370. })
  371. }
  372. testFinish("0")
  373. testFinish("1")
  374. }
  375. func TestException_module(t *testing.T) { testException(t, &testOptions{}) }
  376. func TestException_worker(t *testing.T) {
  377. testException(t, &testOptions{workerScript: "exception.php"})
  378. }
  379. func testException(t *testing.T, opts *testOptions) {
  380. runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) {
  381. req := httptest.NewRequest("GET", fmt.Sprintf("http://example.com/exception.php?i=%d", i), nil)
  382. w := httptest.NewRecorder()
  383. handler(w, req)
  384. resp := w.Result()
  385. body, _ := io.ReadAll(resp.Body)
  386. assert.Contains(t, string(body), "hello")
  387. assert.Contains(t, string(body), fmt.Sprintf(`Uncaught Exception: request %d`, i))
  388. }, opts)
  389. }
  390. func TestEarlyHints_module(t *testing.T) { testEarlyHints(t, &testOptions{}) }
  391. func TestEarlyHints_worker(t *testing.T) {
  392. testEarlyHints(t, &testOptions{workerScript: "early-hints.php"})
  393. }
  394. func testEarlyHints(t *testing.T, opts *testOptions) {
  395. runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) {
  396. var earlyHintReceived bool
  397. trace := &httptrace.ClientTrace{
  398. Got1xxResponse: func(code int, header textproto.MIMEHeader) error {
  399. switch code {
  400. case http.StatusEarlyHints:
  401. assert.Equal(t, "</style.css>; rel=preload; as=style", header.Get("Link"))
  402. assert.Equal(t, strconv.Itoa(i), header.Get("Request"))
  403. earlyHintReceived = true
  404. }
  405. return nil
  406. },
  407. }
  408. req := httptest.NewRequest("GET", fmt.Sprintf("http://example.com/early-hints.php?i=%d", i), nil)
  409. w := NewRecorder()
  410. w.ClientTrace = trace
  411. handler(w, req)
  412. assert.Equal(t, strconv.Itoa(i), w.Header().Get("Request"))
  413. assert.Equal(t, "", w.Header().Get("Link"))
  414. assert.True(t, earlyHintReceived)
  415. }, opts)
  416. }
  417. type streamResponseRecorder struct {
  418. *httptest.ResponseRecorder
  419. writeCallback func(buf []byte)
  420. }
  421. func (srr *streamResponseRecorder) Write(buf []byte) (int, error) {
  422. srr.writeCallback(buf)
  423. return srr.ResponseRecorder.Write(buf)
  424. }
  425. func TestFlush_module(t *testing.T) { testFlush(t, &testOptions{}) }
  426. func TestFlush_worker(t *testing.T) {
  427. testFlush(t, &testOptions{workerScript: "flush.php"})
  428. }
  429. func testFlush(t *testing.T, opts *testOptions) {
  430. runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) {
  431. var j int
  432. req := httptest.NewRequest("GET", fmt.Sprintf("http://example.com/flush.php?i=%d", i), nil)
  433. w := &streamResponseRecorder{httptest.NewRecorder(), func(buf []byte) {
  434. if j == 0 {
  435. assert.Equal(t, []byte("He"), buf)
  436. } else {
  437. assert.Equal(t, []byte(fmt.Sprintf("llo %d", i)), buf)
  438. }
  439. j++
  440. }}
  441. handler(w, req)
  442. assert.Equal(t, 2, j)
  443. }, opts)
  444. }
  445. func TestLargeRequest_module(t *testing.T) {
  446. testLargeRequest(t, &testOptions{})
  447. }
  448. func TestLargeRequest_worker(t *testing.T) {
  449. testLargeRequest(t, &testOptions{workerScript: "large-request.php"})
  450. }
  451. func testLargeRequest(t *testing.T, opts *testOptions) {
  452. runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) {
  453. req := httptest.NewRequest(
  454. "POST",
  455. fmt.Sprintf("http://example.com/large-request.php?i=%d", i),
  456. strings.NewReader(strings.Repeat("f", 6_048_576)),
  457. )
  458. w := httptest.NewRecorder()
  459. handler(w, req)
  460. resp := w.Result()
  461. body, _ := io.ReadAll(resp.Body)
  462. assert.Contains(t, string(body), fmt.Sprintf("Request body size: 6048576 (%d)", i))
  463. }, opts)
  464. }
  465. func TestVersion(t *testing.T) {
  466. v := frankenphp.Version()
  467. assert.GreaterOrEqual(t, v.MajorVersion, 8)
  468. assert.GreaterOrEqual(t, v.MinorVersion, 0)
  469. assert.GreaterOrEqual(t, v.ReleaseVersion, 0)
  470. assert.GreaterOrEqual(t, v.VersionID, 0)
  471. assert.NotEmpty(t, v.Version, 0)
  472. }
  473. func TestFiberNoCgo_module(t *testing.T) { testFiberNoCgo(t, &testOptions{}) }
  474. func TestFiberNonCgo_worker(t *testing.T) {
  475. testFiberNoCgo(t, &testOptions{workerScript: "fiber-no-cgo.php"})
  476. }
  477. func testFiberNoCgo(t *testing.T, opts *testOptions) {
  478. runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) {
  479. req := httptest.NewRequest("GET", fmt.Sprintf("http://example.com/fiber-no-cgo.php?i=%d", i), nil)
  480. w := httptest.NewRecorder()
  481. handler(w, req)
  482. resp := w.Result()
  483. body, _ := io.ReadAll(resp.Body)
  484. assert.Equal(t, string(body), fmt.Sprintf("Fiber %d", i))
  485. }, opts)
  486. }
  487. func TestRequestHeaders_module(t *testing.T) { testRequestHeaders(t, &testOptions{}) }
  488. func TestRequestHeaders_worker(t *testing.T) {
  489. testRequestHeaders(t, &testOptions{workerScript: "request-headers.php"})
  490. }
  491. func testRequestHeaders(t *testing.T, opts *testOptions) {
  492. runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) {
  493. req := httptest.NewRequest("GET", fmt.Sprintf("http://example.com/request-headers.php?i=%d", i), nil)
  494. req.Header.Add(strings.Clone("Content-Type"), strings.Clone("text/plain"))
  495. req.Header.Add(strings.Clone("Frankenphp-I"), strings.Clone(strconv.Itoa(i)))
  496. w := httptest.NewRecorder()
  497. handler(w, req)
  498. resp := w.Result()
  499. body, _ := io.ReadAll(resp.Body)
  500. assert.Contains(t, string(body), "[Content-Type] => text/plain")
  501. assert.Contains(t, string(body), fmt.Sprintf("[Frankenphp-I] => %d", i))
  502. }, opts)
  503. }
  504. func TestExecuteScriptCLI(t *testing.T) {
  505. if _, err := os.Stat("internal/testcli/testcli"); err != nil {
  506. t.Skip("internal/testcli/testcli has not been compiled, run `cd internal/testcli/ && go build`")
  507. }
  508. cmd := exec.Command("internal/testcli/testcli", "testdata/command.php", "foo", "bar")
  509. stdoutStderr, err := cmd.CombinedOutput()
  510. assert.Error(t, err)
  511. if exitError, ok := err.(*exec.ExitError); ok {
  512. assert.Equal(t, 3, exitError.ExitCode())
  513. }
  514. stdoutStderrStr := string(stdoutStderr)
  515. assert.Contains(t, stdoutStderrStr, `"foo"`)
  516. assert.Contains(t, stdoutStderrStr, `"bar"`)
  517. assert.Contains(t, stdoutStderrStr, "From the CLI")
  518. }
  519. func ExampleServeHTTP() {
  520. if err := frankenphp.Init(); err != nil {
  521. panic(err)
  522. }
  523. defer frankenphp.Shutdown()
  524. http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
  525. req, err := frankenphp.NewRequestWithContext(r, frankenphp.WithRequestDocumentRoot("/path/to/document/root", false))
  526. if err != nil {
  527. panic(err)
  528. }
  529. if err := frankenphp.ServeHTTP(w, req); err != nil {
  530. panic(err)
  531. }
  532. })
  533. log.Fatal(http.ListenAndServe(":8080", nil))
  534. }
  535. func ExampleExecuteScriptCLI() {
  536. if len(os.Args) <= 1 {
  537. log.Println("Usage: my-program script.php")
  538. os.Exit(1)
  539. }
  540. os.Exit(frankenphp.ExecuteScriptCLI(os.Args[1], os.Args))
  541. }
  542. func BenchmarkHelloWorld(b *testing.B) {
  543. if err := frankenphp.Init(frankenphp.WithLogger(zap.NewNop())); err != nil {
  544. panic(err)
  545. }
  546. defer frankenphp.Shutdown()
  547. cwd, _ := os.Getwd()
  548. testDataDir := cwd + "/testdata/"
  549. handler := func(w http.ResponseWriter, r *http.Request) {
  550. req, err := frankenphp.NewRequestWithContext(r, frankenphp.WithRequestDocumentRoot(testDataDir, false))
  551. if err != nil {
  552. panic(err)
  553. }
  554. if err := frankenphp.ServeHTTP(w, req); err != nil {
  555. panic(err)
  556. }
  557. }
  558. req := httptest.NewRequest("GET", "http://example.com/index.php", nil)
  559. w := httptest.NewRecorder()
  560. b.ResetTimer()
  561. for i := 0; i < b.N; i++ {
  562. handler(w, req)
  563. }
  564. }
  565. func BenchmarkEcho(b *testing.B) {
  566. if err := frankenphp.Init(frankenphp.WithLogger(zap.NewNop())); err != nil {
  567. panic(err)
  568. }
  569. defer frankenphp.Shutdown()
  570. cwd, _ := os.Getwd()
  571. testDataDir := cwd + "/testdata/"
  572. handler := func(w http.ResponseWriter, r *http.Request) {
  573. req, err := frankenphp.NewRequestWithContext(r, frankenphp.WithRequestDocumentRoot(testDataDir, false))
  574. if err != nil {
  575. panic(err)
  576. }
  577. if err := frankenphp.ServeHTTP(w, req); err != nil {
  578. panic(err)
  579. }
  580. }
  581. const body = `{
  582. "squadName": "Super hero squad",
  583. "homeTown": "Metro City",
  584. "formed": 2016,
  585. "secretBase": "Super tower",
  586. "active": true,
  587. "members": [
  588. {
  589. "name": "Molecule Man",
  590. "age": 29,
  591. "secretIdentity": "Dan Jukes",
  592. "powers": ["Radiation resistance", "Turning tiny", "Radiation blast"]
  593. },
  594. {
  595. "name": "Madame Uppercut",
  596. "age": 39,
  597. "secretIdentity": "Jane Wilson",
  598. "powers": [
  599. "Million tonne punch",
  600. "Damage resistance",
  601. "Superhuman reflexes"
  602. ]
  603. },
  604. {
  605. "name": "Eternal Flame",
  606. "age": 1000000,
  607. "secretIdentity": "Unknown",
  608. "powers": [
  609. "Immortality",
  610. "Heat Immunity",
  611. "Inferno",
  612. "Teleportation",
  613. "Interdimensional travel"
  614. ]
  615. }
  616. ]
  617. }`
  618. r := strings.NewReader(body)
  619. req := httptest.NewRequest("POST", "http://example.com/echo.php", r)
  620. w := httptest.NewRecorder()
  621. b.ResetTimer()
  622. for i := 0; i < b.N; i++ {
  623. r.Reset(body)
  624. handler(w, req)
  625. }
  626. }
  627. func BenchmarkServerSuperGlobal(b *testing.B) {
  628. if err := frankenphp.Init(frankenphp.WithLogger(zap.NewNop())); err != nil {
  629. panic(err)
  630. }
  631. defer frankenphp.Shutdown()
  632. cwd, _ := os.Getwd()
  633. testDataDir := cwd + "/testdata/"
  634. // Mimicks headers of a request sent by Firefox to GitHub
  635. headers := http.Header{}
  636. headers.Add(strings.Clone("Accept"), strings.Clone("text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8"))
  637. headers.Add(strings.Clone("Accept-Encoding"), strings.Clone("gzip, deflate, br"))
  638. headers.Add(strings.Clone("Accept-Language"), strings.Clone("fr,fr-FR;q=0.8,en-US;q=0.5,en;q=0.3"))
  639. headers.Add(strings.Clone("Cache-Control"), strings.Clone("no-cache"))
  640. headers.Add(strings.Clone("Connection"), strings.Clone("keep-alive"))
  641. headers.Add(strings.Clone("Cookie"), strings.Clone("user_session=myrandomuuid; __Host-user_session_same_site=myotherrandomuuid; dotcom_user=dunglas; logged_in=yes; _foo=barbarbarbarbarbar; _device_id=anotherrandomuuid; color_mode=foobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobar; preferred_color_mode=light; tz=Europe%2FParis; has_recent_activity=1"))
  642. headers.Add(strings.Clone("DNT"), strings.Clone("1"))
  643. headers.Add(strings.Clone("Host"), strings.Clone("example.com"))
  644. headers.Add(strings.Clone("Pragma"), strings.Clone("no-cache"))
  645. headers.Add(strings.Clone("Sec-Fetch-Dest"), strings.Clone("document"))
  646. headers.Add(strings.Clone("Sec-Fetch-Mode"), strings.Clone("navigate"))
  647. headers.Add(strings.Clone("Sec-Fetch-Site"), strings.Clone("cross-site"))
  648. headers.Add(strings.Clone("Sec-GPC"), strings.Clone("1"))
  649. headers.Add(strings.Clone("Upgrade-Insecure-Requests"), strings.Clone("1"))
  650. headers.Add(strings.Clone("User-Agent"), strings.Clone("Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:122.0) Gecko/20100101 Firefox/122.0"))
  651. // Env vars available in a typical Docker container
  652. env := map[string]string{
  653. "HOSTNAME": "a88e81aa22e4",
  654. "PHP_INI_DIR": "/usr/local/etc/php",
  655. "HOME": "/root",
  656. "GODEBUG": "cgocheck=0",
  657. "PHP_LDFLAGS": "-Wl,-O1 -pie",
  658. "PHP_CFLAGS": "-fstack-protector-strong -fpic -fpie -O2 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64",
  659. "PHP_VERSION": "8.3.2",
  660. "GPG_KEYS": "1198C0117593497A5EC5C199286AF1F9897469DC C28D937575603EB4ABB725861C0779DC5C0A9DE4 AFD8691FDAEDF03BDF6E460563F15A9B715376CA",
  661. "PHP_CPPFLAGS": "-fstack-protector-strong -fpic -fpie -O2 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64",
  662. "PHP_ASC_URL": "https://www.php.net/distributions/php-8.3.2.tar.xz.asc",
  663. "PHP_URL": "https://www.php.net/distributions/php-8.3.2.tar.xz",
  664. "PATH": "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
  665. "XDG_CONFIG_HOME": "/config",
  666. "XDG_DATA_HOME": "/data",
  667. "PHPIZE_DEPS": "autoconf dpkg-dev file g++ gcc libc-dev make pkg-config re2c",
  668. "PWD": "/app",
  669. "PHP_SHA256": "4ffa3e44afc9c590e28dc0d2d31fc61f0139f8b335f11880a121b9f9b9f0634e",
  670. }
  671. preparedEnv := frankenphp.PrepareEnv(env)
  672. handler := func(w http.ResponseWriter, r *http.Request) {
  673. req, err := frankenphp.NewRequestWithContext(r, frankenphp.WithRequestDocumentRoot(testDataDir, false), frankenphp.WithRequestPreparedEnv(preparedEnv))
  674. if err != nil {
  675. panic(err)
  676. }
  677. r.Header = headers
  678. if err := frankenphp.ServeHTTP(w, req); err != nil {
  679. panic(err)
  680. }
  681. }
  682. req := httptest.NewRequest("GET", "http://example.com/server-variable.php", nil)
  683. w := httptest.NewRecorder()
  684. b.ResetTimer()
  685. for i := 0; i < b.N; i++ {
  686. handler(w, req)
  687. }
  688. }