frankenphp_test.go 33 KB

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