frankenphp_test.go 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964
  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 TestRequestHeaders_module(t *testing.T) { testRequestHeaders(t, &testOptions{}) }
  500. func TestRequestHeaders_worker(t *testing.T) {
  501. testRequestHeaders(t, &testOptions{workerScript: "request-headers.php"})
  502. }
  503. func testRequestHeaders(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/request-headers.php?i=%d", i), nil)
  506. req.Header.Add(strings.Clone("Content-Type"), strings.Clone("text/plain"))
  507. req.Header.Add(strings.Clone("Frankenphp-I"), strings.Clone(strconv.Itoa(i)))
  508. w := httptest.NewRecorder()
  509. handler(w, req)
  510. resp := w.Result()
  511. body, _ := io.ReadAll(resp.Body)
  512. assert.Contains(t, string(body), "[Content-Type] => text/plain")
  513. assert.Contains(t, string(body), fmt.Sprintf("[Frankenphp-I] => %d", i))
  514. }, opts)
  515. }
  516. func TestFailingWorker(t *testing.T) {
  517. runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) {
  518. req := httptest.NewRequest("GET", "http://example.com/failing-worker.php", nil)
  519. w := httptest.NewRecorder()
  520. handler(w, req)
  521. resp := w.Result()
  522. body, _ := io.ReadAll(resp.Body)
  523. assert.Contains(t, string(body), "ok")
  524. }, &testOptions{workerScript: "failing-worker.php"})
  525. }
  526. func TestEnv(t *testing.T) {
  527. testEnv(t, &testOptions{})
  528. }
  529. func TestEnvWorker(t *testing.T) {
  530. testEnv(t, &testOptions{workerScript: "test-env.php"})
  531. }
  532. func testEnv(t *testing.T, opts *testOptions) {
  533. runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) {
  534. req := httptest.NewRequest("GET", fmt.Sprintf("http://example.com/test-env.php?var=%d", i), nil)
  535. w := httptest.NewRecorder()
  536. handler(w, req)
  537. resp := w.Result()
  538. body, _ := io.ReadAll(resp.Body)
  539. // execute the script as regular php script
  540. cmd := exec.Command("php", "testdata/test-env.php", strconv.Itoa(i))
  541. stdoutStderr, err := cmd.CombinedOutput()
  542. if err != nil {
  543. // php is not installed or other issue, use the hardcoded output below:
  544. 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")
  545. }
  546. assert.Equal(t, string(stdoutStderr), string(body))
  547. }, opts)
  548. }
  549. func TestFileUpload_module(t *testing.T) { testFileUpload(t, &testOptions{}) }
  550. func TestFileUpload_worker(t *testing.T) {
  551. testFileUpload(t, &testOptions{workerScript: "file-upload.php"})
  552. }
  553. func testFileUpload(t *testing.T, opts *testOptions) {
  554. runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) {
  555. requestBody := &bytes.Buffer{}
  556. writer := multipart.NewWriter(requestBody)
  557. part, _ := writer.CreateFormFile("file", "foo.txt")
  558. _, err := part.Write([]byte("bar"))
  559. require.NoError(t, err)
  560. writer.Close()
  561. req := httptest.NewRequest("POST", "http://example.com/file-upload.php", requestBody)
  562. req.Header.Add("Content-Type", writer.FormDataContentType())
  563. w := httptest.NewRecorder()
  564. handler(w, req)
  565. resp := w.Result()
  566. body, _ := io.ReadAll(resp.Body)
  567. assert.Contains(t, string(body), "Upload OK")
  568. }, opts)
  569. }
  570. func TestExecuteScriptCLI(t *testing.T) {
  571. if _, err := os.Stat("internal/testcli/testcli"); err != nil {
  572. t.Skip("internal/testcli/testcli has not been compiled, run `cd internal/testcli/ && go build`")
  573. }
  574. cmd := exec.Command("internal/testcli/testcli", "testdata/command.php", "foo", "bar")
  575. stdoutStderr, err := cmd.CombinedOutput()
  576. assert.Error(t, err)
  577. var exitError *exec.ExitError
  578. if errors.As(err, &exitError) {
  579. assert.Equal(t, 3, exitError.ExitCode())
  580. }
  581. stdoutStderrStr := string(stdoutStderr)
  582. assert.Contains(t, stdoutStderrStr, `"foo"`)
  583. assert.Contains(t, stdoutStderrStr, `"bar"`)
  584. assert.Contains(t, stdoutStderrStr, "From the CLI")
  585. }
  586. func ExampleServeHTTP() {
  587. if err := frankenphp.Init(); err != nil {
  588. panic(err)
  589. }
  590. defer frankenphp.Shutdown()
  591. http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
  592. req, err := frankenphp.NewRequestWithContext(r, frankenphp.WithRequestDocumentRoot("/path/to/document/root", false))
  593. if err != nil {
  594. panic(err)
  595. }
  596. if err := frankenphp.ServeHTTP(w, req); err != nil {
  597. panic(err)
  598. }
  599. })
  600. log.Fatal(http.ListenAndServe(":8080", nil))
  601. }
  602. func ExampleExecuteScriptCLI() {
  603. if len(os.Args) <= 1 {
  604. log.Println("Usage: my-program script.php")
  605. os.Exit(1)
  606. }
  607. os.Exit(frankenphp.ExecuteScriptCLI(os.Args[1], os.Args))
  608. }
  609. func BenchmarkHelloWorld(b *testing.B) {
  610. if err := frankenphp.Init(frankenphp.WithLogger(zap.NewNop())); err != nil {
  611. panic(err)
  612. }
  613. defer frankenphp.Shutdown()
  614. cwd, _ := os.Getwd()
  615. testDataDir := cwd + "/testdata/"
  616. handler := func(w http.ResponseWriter, r *http.Request) {
  617. req, err := frankenphp.NewRequestWithContext(r, frankenphp.WithRequestDocumentRoot(testDataDir, false))
  618. if err != nil {
  619. panic(err)
  620. }
  621. if err := frankenphp.ServeHTTP(w, req); err != nil {
  622. panic(err)
  623. }
  624. }
  625. req := httptest.NewRequest("GET", "http://example.com/index.php", nil)
  626. w := httptest.NewRecorder()
  627. b.ResetTimer()
  628. for i := 0; i < b.N; i++ {
  629. handler(w, req)
  630. }
  631. }
  632. func BenchmarkEcho(b *testing.B) {
  633. if err := frankenphp.Init(frankenphp.WithLogger(zap.NewNop())); err != nil {
  634. panic(err)
  635. }
  636. defer frankenphp.Shutdown()
  637. cwd, _ := os.Getwd()
  638. testDataDir := cwd + "/testdata/"
  639. handler := func(w http.ResponseWriter, r *http.Request) {
  640. req, err := frankenphp.NewRequestWithContext(r, frankenphp.WithRequestDocumentRoot(testDataDir, false))
  641. if err != nil {
  642. panic(err)
  643. }
  644. if err := frankenphp.ServeHTTP(w, req); err != nil {
  645. panic(err)
  646. }
  647. }
  648. const body = `{
  649. "squadName": "Super hero squad",
  650. "homeTown": "Metro City",
  651. "formed": 2016,
  652. "secretBase": "Super tower",
  653. "active": true,
  654. "members": [
  655. {
  656. "name": "Molecule Man",
  657. "age": 29,
  658. "secretIdentity": "Dan Jukes",
  659. "powers": ["Radiation resistance", "Turning tiny", "Radiation blast"]
  660. },
  661. {
  662. "name": "Madame Uppercut",
  663. "age": 39,
  664. "secretIdentity": "Jane Wilson",
  665. "powers": [
  666. "Million tonne punch",
  667. "Damage resistance",
  668. "Superhuman reflexes"
  669. ]
  670. },
  671. {
  672. "name": "Eternal Flame",
  673. "age": 1000000,
  674. "secretIdentity": "Unknown",
  675. "powers": [
  676. "Immortality",
  677. "Heat Immunity",
  678. "Inferno",
  679. "Teleportation",
  680. "Interdimensional travel"
  681. ]
  682. }
  683. ]
  684. }`
  685. r := strings.NewReader(body)
  686. req := httptest.NewRequest("POST", "http://example.com/echo.php", r)
  687. w := httptest.NewRecorder()
  688. b.ResetTimer()
  689. for i := 0; i < b.N; i++ {
  690. r.Reset(body)
  691. handler(w, req)
  692. }
  693. }
  694. func BenchmarkServerSuperGlobal(b *testing.B) {
  695. if err := frankenphp.Init(frankenphp.WithLogger(zap.NewNop())); err != nil {
  696. panic(err)
  697. }
  698. defer frankenphp.Shutdown()
  699. cwd, _ := os.Getwd()
  700. testDataDir := cwd + "/testdata/"
  701. // Mimicks headers of a request sent by Firefox to GitHub
  702. headers := http.Header{}
  703. headers.Add(strings.Clone("Accept"), strings.Clone("text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8"))
  704. headers.Add(strings.Clone("Accept-Encoding"), strings.Clone("gzip, deflate, br"))
  705. headers.Add(strings.Clone("Accept-Language"), strings.Clone("fr,fr-FR;q=0.8,en-US;q=0.5,en;q=0.3"))
  706. headers.Add(strings.Clone("Cache-Control"), strings.Clone("no-cache"))
  707. headers.Add(strings.Clone("Connection"), strings.Clone("keep-alive"))
  708. 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"))
  709. headers.Add(strings.Clone("DNT"), strings.Clone("1"))
  710. headers.Add(strings.Clone("Host"), strings.Clone("example.com"))
  711. headers.Add(strings.Clone("Pragma"), strings.Clone("no-cache"))
  712. headers.Add(strings.Clone("Sec-Fetch-Dest"), strings.Clone("document"))
  713. headers.Add(strings.Clone("Sec-Fetch-Mode"), strings.Clone("navigate"))
  714. headers.Add(strings.Clone("Sec-Fetch-Site"), strings.Clone("cross-site"))
  715. headers.Add(strings.Clone("Sec-GPC"), strings.Clone("1"))
  716. headers.Add(strings.Clone("Upgrade-Insecure-Requests"), strings.Clone("1"))
  717. 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"))
  718. // Env vars available in a typical Docker container
  719. env := map[string]string{
  720. "HOSTNAME": "a88e81aa22e4",
  721. "PHP_INI_DIR": "/usr/local/etc/php",
  722. "HOME": "/root",
  723. "GODEBUG": "cgocheck=0",
  724. "PHP_LDFLAGS": "-Wl,-O1 -pie",
  725. "PHP_CFLAGS": "-fstack-protector-strong -fpic -fpie -O2 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64",
  726. "PHP_VERSION": "8.3.2",
  727. "GPG_KEYS": "1198C0117593497A5EC5C199286AF1F9897469DC C28D937575603EB4ABB725861C0779DC5C0A9DE4 AFD8691FDAEDF03BDF6E460563F15A9B715376CA",
  728. "PHP_CPPFLAGS": "-fstack-protector-strong -fpic -fpie -O2 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64",
  729. "PHP_ASC_URL": "https://www.php.net/distributions/php-8.3.2.tar.xz.asc",
  730. "PHP_URL": "https://www.php.net/distributions/php-8.3.2.tar.xz",
  731. "PATH": "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
  732. "XDG_CONFIG_HOME": "/config",
  733. "XDG_DATA_HOME": "/data",
  734. "PHPIZE_DEPS": "autoconf dpkg-dev file g++ gcc libc-dev make pkg-config re2c",
  735. "PWD": "/app",
  736. "PHP_SHA256": "4ffa3e44afc9c590e28dc0d2d31fc61f0139f8b335f11880a121b9f9b9f0634e",
  737. }
  738. preparedEnv := frankenphp.PrepareEnv(env)
  739. handler := func(w http.ResponseWriter, r *http.Request) {
  740. req, err := frankenphp.NewRequestWithContext(r, frankenphp.WithRequestDocumentRoot(testDataDir, false), frankenphp.WithRequestPreparedEnv(preparedEnv))
  741. if err != nil {
  742. panic(err)
  743. }
  744. r.Header = headers
  745. if err := frankenphp.ServeHTTP(w, req); err != nil {
  746. panic(err)
  747. }
  748. }
  749. req := httptest.NewRequest("GET", "http://example.com/server-variable.php", nil)
  750. w := httptest.NewRecorder()
  751. b.ResetTimer()
  752. for i := 0; i < b.N; i++ {
  753. handler(w, req)
  754. }
  755. }
  756. func TestRejectInvalidHeaders_module(t *testing.T) { testRejectInvalidHeaders(t, &testOptions{}) }
  757. func TestRejectInvalidHeaders_worker(t *testing.T) {
  758. testRejectInvalidHeaders(t, &testOptions{workerScript: "headers.php"})
  759. }
  760. func testRejectInvalidHeaders(t *testing.T, opts *testOptions) {
  761. invalidHeaders := [][]string{
  762. {"Content-Length", "-1"},
  763. {"Content-Length", "something"},
  764. }
  765. for _, header := range invalidHeaders {
  766. runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, _ int) {
  767. req := httptest.NewRequest("GET", "http://example.com/headers.php", nil)
  768. req.Header.Add(header[0], header[1])
  769. w := httptest.NewRecorder()
  770. handler(w, req)
  771. resp := w.Result()
  772. body, _ := io.ReadAll(resp.Body)
  773. assert.Equal(t, 400, resp.StatusCode)
  774. assert.Contains(t, string(body), "invalid")
  775. }, opts)
  776. }
  777. }
  778. // To run this fuzzing test use: go test -fuzz FuzzRequest
  779. // TODO: Cover more potential cases
  780. func FuzzRequest(f *testing.F) {
  781. absPath, _ := fastabs.FastAbs("./testdata/")
  782. f.Add("hello world")
  783. f.Add("πŸ˜€πŸ˜…πŸ™ƒπŸ€©πŸ₯²πŸ€ͺπŸ˜˜πŸ˜‡πŸ˜‰πŸ˜πŸ§Ÿ")
  784. f.Add("%00%11%%22%%33%%44%%55%%66%%77%%88%%99%%aa%%bb%%cc%%dd%%ee%%ff")
  785. f.Add("\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f")
  786. f.Fuzz(func(t *testing.T, fuzzedString string) {
  787. runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, _ int) {
  788. req := httptest.NewRequest("GET", "http://example.com/server-variable", nil)
  789. req.URL = &url.URL{RawQuery: "test=" + fuzzedString, Path: "/server-variable.php/" + fuzzedString}
  790. req.Header.Add(strings.Clone("Fuzzed"), strings.Clone(fuzzedString))
  791. req.Header.Add(strings.Clone("Content-Type"), fuzzedString)
  792. w := httptest.NewRecorder()
  793. handler(w, req)
  794. resp := w.Result()
  795. body, _ := io.ReadAll(resp.Body)
  796. // The response status must be 400 if the request path contains null bytes
  797. if strings.Contains(req.URL.Path, "\x00") {
  798. assert.Equal(t, 400, resp.StatusCode)
  799. assert.Contains(t, string(body), "Invalid request path")
  800. return
  801. }
  802. // The fuzzed string must be present in the path
  803. assert.Contains(t, string(body), fmt.Sprintf("[PATH_INFO] => /%s", fuzzedString))
  804. assert.Contains(t, string(body), fmt.Sprintf("[PATH_TRANSLATED] => %s", filepath.Join(absPath, fuzzedString)))
  805. // The header should only be present if the fuzzed string is not empty
  806. if len(fuzzedString) > 0 {
  807. assert.Contains(t, string(body), fmt.Sprintf("[CONTENT_TYPE] => %s", fuzzedString))
  808. assert.Contains(t, string(body), fmt.Sprintf("[HTTP_FUZZED] => %s", fuzzedString))
  809. } else {
  810. assert.NotContains(t, string(body), "[HTTP_FUZZED]")
  811. }
  812. }, &testOptions{workerScript: "request-headers.php"})
  813. })
  814. }