frankenphp_test.go 28 KB

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