frankenphp_test.go 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998
  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 occurring 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. nbParallelRequests 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.nbParallelRequests == 0 {
  50. opts.nbParallelRequests = 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.nbParallelRequests)
  78. for i := 0; i < opts.nbParallelRequests; 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 TestMalformedCookie(t *testing.T) {
  277. runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) {
  278. req := httptest.NewRequest("GET", "http://example.com/cookies.php", nil)
  279. req.Header.Add("Cookie", "foo =bar; ===;;==; .dot.=val ;\x00 ; PHPSESSID=1234")
  280. w := httptest.NewRecorder()
  281. handler(w, req)
  282. resp := w.Result()
  283. body, _ := io.ReadAll(resp.Body)
  284. assert.Contains(t, string(body), "'foo_' => 'bar'")
  285. assert.Contains(t, string(body), "'_dot_' => 'val '")
  286. // PHPSESSID should still be present since we remove the null byte
  287. assert.Contains(t, string(body), "'PHPSESSID' => '1234'")
  288. }, &testOptions{nbParallelRequests: 1})
  289. }
  290. func TestSession_module(t *testing.T) { testSession(t, nil) }
  291. func TestSession_worker(t *testing.T) {
  292. testSession(t, &testOptions{workerScript: "session.php"})
  293. }
  294. func testSession(t *testing.T, opts *testOptions) {
  295. if opts == nil {
  296. opts = &testOptions{}
  297. }
  298. opts.realServer = true
  299. runTest(t, func(_ func(http.ResponseWriter, *http.Request), ts *httptest.Server, i int) {
  300. jar, err := cookiejar.New(&cookiejar.Options{})
  301. assert.NoError(t, err)
  302. client := &http.Client{Jar: jar}
  303. resp1, err := client.Get(ts.URL + "/session.php")
  304. assert.NoError(t, err)
  305. body1, _ := io.ReadAll(resp1.Body)
  306. assert.Equal(t, "Count: 0\n", string(body1))
  307. resp2, err := client.Get(ts.URL + "/session.php")
  308. assert.NoError(t, err)
  309. body2, _ := io.ReadAll(resp2.Body)
  310. assert.Equal(t, "Count: 1\n", string(body2))
  311. }, opts)
  312. }
  313. func TestPhpInfo_module(t *testing.T) { testPhpInfo(t, nil) }
  314. func TestPhpInfo_worker(t *testing.T) { testPhpInfo(t, &testOptions{workerScript: "phpinfo.php"}) }
  315. func testPhpInfo(t *testing.T, opts *testOptions) {
  316. var logOnce sync.Once
  317. runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) {
  318. req := httptest.NewRequest("GET", fmt.Sprintf("http://example.com/phpinfo.php?i=%d", i), nil)
  319. w := httptest.NewRecorder()
  320. handler(w, req)
  321. resp := w.Result()
  322. body, _ := io.ReadAll(resp.Body)
  323. logOnce.Do(func() {
  324. t.Log(string(body))
  325. })
  326. assert.Contains(t, string(body), "frankenphp")
  327. assert.Contains(t, string(body), fmt.Sprintf("i=%d", i))
  328. }, opts)
  329. }
  330. func TestPersistentObject_module(t *testing.T) { testPersistentObject(t, nil) }
  331. func TestPersistentObject_worker(t *testing.T) {
  332. testPersistentObject(t, &testOptions{workerScript: "persistent-object.php"})
  333. }
  334. func testPersistentObject(t *testing.T, opts *testOptions) {
  335. runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) {
  336. req := httptest.NewRequest("GET", fmt.Sprintf("http://example.com/persistent-object.php?i=%d", i), nil)
  337. w := httptest.NewRecorder()
  338. handler(w, req)
  339. resp := w.Result()
  340. body, _ := io.ReadAll(resp.Body)
  341. assert.Equal(t, fmt.Sprintf(`request: %d
  342. class exists: 1
  343. id: obj1
  344. object id: 1`, i), string(body))
  345. }, opts)
  346. }
  347. func TestAutoloader_module(t *testing.T) { testAutoloader(t, nil) }
  348. func TestAutoloader_worker(t *testing.T) {
  349. testAutoloader(t, &testOptions{workerScript: "autoloader.php"})
  350. }
  351. func testAutoloader(t *testing.T, opts *testOptions) {
  352. runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) {
  353. req := httptest.NewRequest("GET", fmt.Sprintf("http://example.com/autoloader.php?i=%d", i), nil)
  354. w := httptest.NewRecorder()
  355. handler(w, req)
  356. resp := w.Result()
  357. body, _ := io.ReadAll(resp.Body)
  358. assert.Equal(t, fmt.Sprintf(`request %d
  359. my_autoloader`, i), string(body))
  360. }, opts)
  361. }
  362. func TestLog_module(t *testing.T) { testLog(t, &testOptions{}) }
  363. func TestLog_worker(t *testing.T) {
  364. testLog(t, &testOptions{workerScript: "log.php"})
  365. }
  366. func testLog(t *testing.T, opts *testOptions) {
  367. logger, logs := observer.New(zapcore.InfoLevel)
  368. opts.logger = zap.New(logger)
  369. runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) {
  370. req := httptest.NewRequest("GET", fmt.Sprintf("http://example.com/log.php?i=%d", i), nil)
  371. w := httptest.NewRecorder()
  372. handler(w, req)
  373. for logs.FilterMessage(fmt.Sprintf("request %d", i)).Len() <= 0 {
  374. }
  375. }, opts)
  376. }
  377. func TestConnectionAbort_module(t *testing.T) { testConnectionAbort(t, &testOptions{}) }
  378. func TestConnectionAbort_worker(t *testing.T) {
  379. testConnectionAbort(t, &testOptions{workerScript: "connectionStatusLog.php"})
  380. }
  381. func testConnectionAbort(t *testing.T, opts *testOptions) {
  382. testFinish := func(finish string) {
  383. t.Run(fmt.Sprintf("finish=%s", finish), func(t *testing.T) {
  384. logger, logs := observer.New(zapcore.InfoLevel)
  385. opts.logger = zap.New(logger)
  386. runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) {
  387. req := httptest.NewRequest("GET", fmt.Sprintf("http://example.com/connectionStatusLog.php?i=%d&finish=%s", i, finish), nil)
  388. w := httptest.NewRecorder()
  389. ctx, cancel := context.WithCancel(req.Context())
  390. req = req.WithContext(ctx)
  391. cancel()
  392. handler(w, req)
  393. for logs.FilterMessage(fmt.Sprintf("request %d: 1", i)).Len() <= 0 {
  394. }
  395. }, opts)
  396. })
  397. }
  398. testFinish("0")
  399. testFinish("1")
  400. }
  401. func TestException_module(t *testing.T) { testException(t, &testOptions{}) }
  402. func TestException_worker(t *testing.T) {
  403. testException(t, &testOptions{workerScript: "exception.php"})
  404. }
  405. func testException(t *testing.T, opts *testOptions) {
  406. runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) {
  407. req := httptest.NewRequest("GET", fmt.Sprintf("http://example.com/exception.php?i=%d", i), nil)
  408. w := httptest.NewRecorder()
  409. handler(w, req)
  410. resp := w.Result()
  411. body, _ := io.ReadAll(resp.Body)
  412. assert.Contains(t, string(body), "hello")
  413. assert.Contains(t, string(body), fmt.Sprintf(`Uncaught Exception: request %d`, i))
  414. }, opts)
  415. }
  416. func TestEarlyHints_module(t *testing.T) { testEarlyHints(t, &testOptions{}) }
  417. func TestEarlyHints_worker(t *testing.T) {
  418. testEarlyHints(t, &testOptions{workerScript: "early-hints.php"})
  419. }
  420. func testEarlyHints(t *testing.T, opts *testOptions) {
  421. runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) {
  422. var earlyHintReceived bool
  423. trace := &httptrace.ClientTrace{
  424. Got1xxResponse: func(code int, header textproto.MIMEHeader) error {
  425. switch code {
  426. case http.StatusEarlyHints:
  427. assert.Equal(t, "</style.css>; rel=preload; as=style", header.Get("Link"))
  428. assert.Equal(t, strconv.Itoa(i), header.Get("Request"))
  429. earlyHintReceived = true
  430. }
  431. return nil
  432. },
  433. }
  434. req := httptest.NewRequest("GET", fmt.Sprintf("http://example.com/early-hints.php?i=%d", i), nil)
  435. w := NewRecorder()
  436. w.ClientTrace = trace
  437. handler(w, req)
  438. assert.Equal(t, strconv.Itoa(i), w.Header().Get("Request"))
  439. assert.Equal(t, "", w.Header().Get("Link"))
  440. assert.True(t, earlyHintReceived)
  441. }, opts)
  442. }
  443. type streamResponseRecorder struct {
  444. *httptest.ResponseRecorder
  445. writeCallback func(buf []byte)
  446. }
  447. func (srr *streamResponseRecorder) Write(buf []byte) (int, error) {
  448. srr.writeCallback(buf)
  449. return srr.ResponseRecorder.Write(buf)
  450. }
  451. func TestFlush_module(t *testing.T) { testFlush(t, &testOptions{}) }
  452. func TestFlush_worker(t *testing.T) {
  453. testFlush(t, &testOptions{workerScript: "flush.php"})
  454. }
  455. func testFlush(t *testing.T, opts *testOptions) {
  456. runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) {
  457. var j int
  458. req := httptest.NewRequest("GET", fmt.Sprintf("http://example.com/flush.php?i=%d", i), nil)
  459. w := &streamResponseRecorder{httptest.NewRecorder(), func(buf []byte) {
  460. if j == 0 {
  461. assert.Equal(t, []byte("He"), buf)
  462. } else {
  463. assert.Equal(t, []byte(fmt.Sprintf("llo %d", i)), buf)
  464. }
  465. j++
  466. }}
  467. handler(w, req)
  468. assert.Equal(t, 2, j)
  469. }, opts)
  470. }
  471. func TestLargeRequest_module(t *testing.T) {
  472. testLargeRequest(t, &testOptions{})
  473. }
  474. func TestLargeRequest_worker(t *testing.T) {
  475. testLargeRequest(t, &testOptions{workerScript: "large-request.php"})
  476. }
  477. func testLargeRequest(t *testing.T, opts *testOptions) {
  478. runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) {
  479. req := httptest.NewRequest(
  480. "POST",
  481. fmt.Sprintf("http://example.com/large-request.php?i=%d", i),
  482. strings.NewReader(strings.Repeat("f", 6_048_576)),
  483. )
  484. w := httptest.NewRecorder()
  485. handler(w, req)
  486. resp := w.Result()
  487. body, _ := io.ReadAll(resp.Body)
  488. assert.Contains(t, string(body), fmt.Sprintf("Request body size: 6048576 (%d)", i))
  489. }, opts)
  490. }
  491. func TestVersion(t *testing.T) {
  492. v := frankenphp.Version()
  493. assert.GreaterOrEqual(t, v.MajorVersion, 8)
  494. assert.GreaterOrEqual(t, v.MinorVersion, 0)
  495. assert.GreaterOrEqual(t, v.ReleaseVersion, 0)
  496. assert.GreaterOrEqual(t, v.VersionID, 0)
  497. assert.NotEmpty(t, v.Version, 0)
  498. }
  499. func TestFiberNoCgo_module(t *testing.T) { testFiberNoCgo(t, &testOptions{}) }
  500. func TestFiberNonCgo_worker(t *testing.T) {
  501. testFiberNoCgo(t, &testOptions{workerScript: "fiber-no-cgo.php"})
  502. }
  503. func testFiberNoCgo(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-no-cgo.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 TestFiberBasic_module(t *testing.T) { testFiberBasic(t, &testOptions{}) }
  514. func TestFiberBasic_worker(t *testing.T) {
  515. testFiberBasic(t, &testOptions{workerScript: "fiber-basic.php"})
  516. }
  517. func testFiberBasic(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/fiber-basic.php?i=%d", i), nil)
  520. w := httptest.NewRecorder()
  521. handler(w, req)
  522. resp := w.Result()
  523. body, _ := io.ReadAll(resp.Body)
  524. assert.Equal(t, string(body), fmt.Sprintf("Fiber %d", i))
  525. }, opts)
  526. }
  527. func TestRequestHeaders_module(t *testing.T) { testRequestHeaders(t, &testOptions{}) }
  528. func TestRequestHeaders_worker(t *testing.T) {
  529. testRequestHeaders(t, &testOptions{workerScript: "request-headers.php"})
  530. }
  531. func testRequestHeaders(t *testing.T, opts *testOptions) {
  532. runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) {
  533. req := httptest.NewRequest("GET", fmt.Sprintf("http://example.com/request-headers.php?i=%d", i), nil)
  534. req.Header.Add(strings.Clone("Content-Type"), strings.Clone("text/plain"))
  535. req.Header.Add(strings.Clone("Frankenphp-I"), strings.Clone(strconv.Itoa(i)))
  536. w := httptest.NewRecorder()
  537. handler(w, req)
  538. resp := w.Result()
  539. body, _ := io.ReadAll(resp.Body)
  540. assert.Contains(t, string(body), "[Content-Type] => text/plain")
  541. assert.Contains(t, string(body), fmt.Sprintf("[Frankenphp-I] => %d", i))
  542. }, opts)
  543. }
  544. func TestFailingWorker(t *testing.T) {
  545. runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) {
  546. req := httptest.NewRequest("GET", "http://example.com/failing-worker.php", nil)
  547. w := httptest.NewRecorder()
  548. handler(w, req)
  549. resp := w.Result()
  550. body, _ := io.ReadAll(resp.Body)
  551. assert.Contains(t, string(body), "ok")
  552. }, &testOptions{workerScript: "failing-worker.php"})
  553. }
  554. func TestEnv(t *testing.T) {
  555. testEnv(t, &testOptions{})
  556. }
  557. func TestEnvWorker(t *testing.T) {
  558. testEnv(t, &testOptions{workerScript: "test-env.php"})
  559. }
  560. func testEnv(t *testing.T, opts *testOptions) {
  561. assert.NoError(t, os.Setenv("EMPTY", ""))
  562. runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) {
  563. req := httptest.NewRequest("GET", fmt.Sprintf("http://example.com/test-env.php?var=%d", i), nil)
  564. w := httptest.NewRecorder()
  565. handler(w, req)
  566. resp := w.Result()
  567. body, _ := io.ReadAll(resp.Body)
  568. // execute the script as regular php script
  569. cmd := exec.Command("php", "testdata/test-env.php", strconv.Itoa(i))
  570. stdoutStderr, err := cmd.CombinedOutput()
  571. if err != nil {
  572. // php is not installed or other issue, use the hardcoded output below:
  573. 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")
  574. }
  575. assert.Equal(t, string(stdoutStderr), string(body))
  576. }, opts)
  577. }
  578. func TestFileUpload_module(t *testing.T) { testFileUpload(t, &testOptions{}) }
  579. func TestFileUpload_worker(t *testing.T) {
  580. testFileUpload(t, &testOptions{workerScript: "file-upload.php"})
  581. }
  582. func testFileUpload(t *testing.T, opts *testOptions) {
  583. runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) {
  584. requestBody := &bytes.Buffer{}
  585. writer := multipart.NewWriter(requestBody)
  586. part, _ := writer.CreateFormFile("file", "foo.txt")
  587. _, err := part.Write([]byte("bar"))
  588. require.NoError(t, err)
  589. writer.Close()
  590. req := httptest.NewRequest("POST", "http://example.com/file-upload.php", requestBody)
  591. req.Header.Add("Content-Type", writer.FormDataContentType())
  592. w := httptest.NewRecorder()
  593. handler(w, req)
  594. resp := w.Result()
  595. body, _ := io.ReadAll(resp.Body)
  596. assert.Contains(t, string(body), "Upload OK")
  597. }, opts)
  598. }
  599. func TestExecuteScriptCLI(t *testing.T) {
  600. if _, err := os.Stat("internal/testcli/testcli"); err != nil {
  601. t.Skip("internal/testcli/testcli has not been compiled, run `cd internal/testcli/ && go build`")
  602. }
  603. cmd := exec.Command("internal/testcli/testcli", "testdata/command.php", "foo", "bar")
  604. stdoutStderr, err := cmd.CombinedOutput()
  605. assert.Error(t, err)
  606. var exitError *exec.ExitError
  607. if errors.As(err, &exitError) {
  608. assert.Equal(t, 3, exitError.ExitCode())
  609. }
  610. stdoutStderrStr := string(stdoutStderr)
  611. assert.Contains(t, stdoutStderrStr, `"foo"`)
  612. assert.Contains(t, stdoutStderrStr, `"bar"`)
  613. assert.Contains(t, stdoutStderrStr, "From the CLI")
  614. }
  615. func ExampleServeHTTP() {
  616. if err := frankenphp.Init(); err != nil {
  617. panic(err)
  618. }
  619. defer frankenphp.Shutdown()
  620. http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
  621. req, err := frankenphp.NewRequestWithContext(r, frankenphp.WithRequestDocumentRoot("/path/to/document/root", false))
  622. if err != nil {
  623. panic(err)
  624. }
  625. if err := frankenphp.ServeHTTP(w, req); err != nil {
  626. panic(err)
  627. }
  628. })
  629. log.Fatal(http.ListenAndServe(":8080", nil))
  630. }
  631. func ExampleExecuteScriptCLI() {
  632. if len(os.Args) <= 1 {
  633. log.Println("Usage: my-program script.php")
  634. os.Exit(1)
  635. }
  636. os.Exit(frankenphp.ExecuteScriptCLI(os.Args[1], os.Args))
  637. }
  638. func BenchmarkHelloWorld(b *testing.B) {
  639. if err := frankenphp.Init(frankenphp.WithLogger(zap.NewNop())); err != nil {
  640. panic(err)
  641. }
  642. defer frankenphp.Shutdown()
  643. cwd, _ := os.Getwd()
  644. testDataDir := cwd + "/testdata/"
  645. handler := func(w http.ResponseWriter, r *http.Request) {
  646. req, err := frankenphp.NewRequestWithContext(r, frankenphp.WithRequestDocumentRoot(testDataDir, false))
  647. if err != nil {
  648. panic(err)
  649. }
  650. if err := frankenphp.ServeHTTP(w, req); err != nil {
  651. panic(err)
  652. }
  653. }
  654. req := httptest.NewRequest("GET", "http://example.com/index.php", nil)
  655. w := httptest.NewRecorder()
  656. b.ResetTimer()
  657. for i := 0; i < b.N; i++ {
  658. handler(w, req)
  659. }
  660. }
  661. func BenchmarkEcho(b *testing.B) {
  662. if err := frankenphp.Init(frankenphp.WithLogger(zap.NewNop())); err != nil {
  663. panic(err)
  664. }
  665. defer frankenphp.Shutdown()
  666. cwd, _ := os.Getwd()
  667. testDataDir := cwd + "/testdata/"
  668. handler := func(w http.ResponseWriter, r *http.Request) {
  669. req, err := frankenphp.NewRequestWithContext(r, frankenphp.WithRequestDocumentRoot(testDataDir, false))
  670. if err != nil {
  671. panic(err)
  672. }
  673. if err := frankenphp.ServeHTTP(w, req); err != nil {
  674. panic(err)
  675. }
  676. }
  677. const body = `{
  678. "squadName": "Super hero squad",
  679. "homeTown": "Metro City",
  680. "formed": 2016,
  681. "secretBase": "Super tower",
  682. "active": true,
  683. "members": [
  684. {
  685. "name": "Molecule Man",
  686. "age": 29,
  687. "secretIdentity": "Dan Jukes",
  688. "powers": ["Radiation resistance", "Turning tiny", "Radiation blast"]
  689. },
  690. {
  691. "name": "Madame Uppercut",
  692. "age": 39,
  693. "secretIdentity": "Jane Wilson",
  694. "powers": [
  695. "Million tonne punch",
  696. "Damage resistance",
  697. "Superhuman reflexes"
  698. ]
  699. },
  700. {
  701. "name": "Eternal Flame",
  702. "age": 1000000,
  703. "secretIdentity": "Unknown",
  704. "powers": [
  705. "Immortality",
  706. "Heat Immunity",
  707. "Inferno",
  708. "Teleportation",
  709. "Interdimensional travel"
  710. ]
  711. }
  712. ]
  713. }`
  714. r := strings.NewReader(body)
  715. req := httptest.NewRequest("POST", "http://example.com/echo.php", r)
  716. w := httptest.NewRecorder()
  717. b.ResetTimer()
  718. for i := 0; i < b.N; i++ {
  719. r.Reset(body)
  720. handler(w, req)
  721. }
  722. }
  723. func BenchmarkServerSuperGlobal(b *testing.B) {
  724. if err := frankenphp.Init(frankenphp.WithLogger(zap.NewNop())); err != nil {
  725. panic(err)
  726. }
  727. defer frankenphp.Shutdown()
  728. cwd, _ := os.Getwd()
  729. testDataDir := cwd + "/testdata/"
  730. // Mimics headers of a request sent by Firefox to GitHub
  731. headers := http.Header{}
  732. headers.Add(strings.Clone("Accept"), strings.Clone("text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8"))
  733. headers.Add(strings.Clone("Accept-Encoding"), strings.Clone("gzip, deflate, br"))
  734. headers.Add(strings.Clone("Accept-Language"), strings.Clone("fr,fr-FR;q=0.8,en-US;q=0.5,en;q=0.3"))
  735. headers.Add(strings.Clone("Cache-Control"), strings.Clone("no-cache"))
  736. headers.Add(strings.Clone("Connection"), strings.Clone("keep-alive"))
  737. 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"))
  738. headers.Add(strings.Clone("DNT"), strings.Clone("1"))
  739. headers.Add(strings.Clone("Host"), strings.Clone("example.com"))
  740. headers.Add(strings.Clone("Pragma"), strings.Clone("no-cache"))
  741. headers.Add(strings.Clone("Sec-Fetch-Dest"), strings.Clone("document"))
  742. headers.Add(strings.Clone("Sec-Fetch-Mode"), strings.Clone("navigate"))
  743. headers.Add(strings.Clone("Sec-Fetch-Site"), strings.Clone("cross-site"))
  744. headers.Add(strings.Clone("Sec-GPC"), strings.Clone("1"))
  745. headers.Add(strings.Clone("Upgrade-Insecure-Requests"), strings.Clone("1"))
  746. 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"))
  747. // Env vars available in a typical Docker container
  748. env := map[string]string{
  749. "HOSTNAME": "a88e81aa22e4",
  750. "PHP_INI_DIR": "/usr/local/etc/php",
  751. "HOME": "/root",
  752. "GODEBUG": "cgocheck=0",
  753. "PHP_LDFLAGS": "-Wl,-O1 -pie",
  754. "PHP_CFLAGS": "-fstack-protector-strong -fpic -fpie -O2 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64",
  755. "PHP_VERSION": "8.3.2",
  756. "GPG_KEYS": "1198C0117593497A5EC5C199286AF1F9897469DC C28D937575603EB4ABB725861C0779DC5C0A9DE4 AFD8691FDAEDF03BDF6E460563F15A9B715376CA",
  757. "PHP_CPPFLAGS": "-fstack-protector-strong -fpic -fpie -O2 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64",
  758. "PHP_ASC_URL": "https://www.php.net/distributions/php-8.3.2.tar.xz.asc",
  759. "PHP_URL": "https://www.php.net/distributions/php-8.3.2.tar.xz",
  760. "PATH": "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
  761. "XDG_CONFIG_HOME": "/config",
  762. "XDG_DATA_HOME": "/data",
  763. "PHPIZE_DEPS": "autoconf dpkg-dev file g++ gcc libc-dev make pkg-config re2c",
  764. "PWD": "/app",
  765. "PHP_SHA256": "4ffa3e44afc9c590e28dc0d2d31fc61f0139f8b335f11880a121b9f9b9f0634e",
  766. }
  767. preparedEnv := frankenphp.PrepareEnv(env)
  768. handler := func(w http.ResponseWriter, r *http.Request) {
  769. req, err := frankenphp.NewRequestWithContext(r, frankenphp.WithRequestDocumentRoot(testDataDir, false), frankenphp.WithRequestPreparedEnv(preparedEnv))
  770. if err != nil {
  771. panic(err)
  772. }
  773. r.Header = headers
  774. if err := frankenphp.ServeHTTP(w, req); err != nil {
  775. panic(err)
  776. }
  777. }
  778. req := httptest.NewRequest("GET", "http://example.com/server-variable.php", nil)
  779. w := httptest.NewRecorder()
  780. b.ResetTimer()
  781. for i := 0; i < b.N; i++ {
  782. handler(w, req)
  783. }
  784. }
  785. func TestRejectInvalidHeaders_module(t *testing.T) { testRejectInvalidHeaders(t, &testOptions{}) }
  786. func TestRejectInvalidHeaders_worker(t *testing.T) {
  787. testRejectInvalidHeaders(t, &testOptions{workerScript: "headers.php"})
  788. }
  789. func testRejectInvalidHeaders(t *testing.T, opts *testOptions) {
  790. invalidHeaders := [][]string{
  791. {"Content-Length", "-1"},
  792. {"Content-Length", "something"},
  793. }
  794. for _, header := range invalidHeaders {
  795. runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, _ int) {
  796. req := httptest.NewRequest("GET", "http://example.com/headers.php", nil)
  797. req.Header.Add(header[0], header[1])
  798. w := httptest.NewRecorder()
  799. handler(w, req)
  800. resp := w.Result()
  801. body, _ := io.ReadAll(resp.Body)
  802. assert.Equal(t, 400, resp.StatusCode)
  803. assert.Contains(t, string(body), "invalid")
  804. }, opts)
  805. }
  806. }
  807. // To run this fuzzing test use: go test -fuzz FuzzRequest
  808. // TODO: Cover more potential cases
  809. func FuzzRequest(f *testing.F) {
  810. absPath, _ := fastabs.FastAbs("./testdata/")
  811. f.Add("hello world")
  812. f.Add("πŸ˜€πŸ˜…πŸ™ƒπŸ€©πŸ₯²πŸ€ͺπŸ˜˜πŸ˜‡πŸ˜‰πŸ˜πŸ§Ÿ")
  813. f.Add("%00%11%%22%%33%%44%%55%%66%%77%%88%%99%%aa%%bb%%cc%%dd%%ee%%ff")
  814. f.Add("\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f")
  815. f.Fuzz(func(t *testing.T, fuzzedString string) {
  816. runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, _ int) {
  817. req := httptest.NewRequest("GET", "http://example.com/server-variable", nil)
  818. req.URL = &url.URL{RawQuery: "test=" + fuzzedString, Path: "/server-variable.php/" + fuzzedString}
  819. req.Header.Add(strings.Clone("Fuzzed"), strings.Clone(fuzzedString))
  820. req.Header.Add(strings.Clone("Content-Type"), fuzzedString)
  821. w := httptest.NewRecorder()
  822. handler(w, req)
  823. resp := w.Result()
  824. body, _ := io.ReadAll(resp.Body)
  825. // The response status must be 400 if the request path contains null bytes
  826. if strings.Contains(req.URL.Path, "\x00") {
  827. assert.Equal(t, 400, resp.StatusCode)
  828. assert.Contains(t, string(body), "Invalid request path")
  829. return
  830. }
  831. // The fuzzed string must be present in the path
  832. assert.Contains(t, string(body), fmt.Sprintf("[PATH_INFO] => /%s", fuzzedString))
  833. assert.Contains(t, string(body), fmt.Sprintf("[PATH_TRANSLATED] => %s", filepath.Join(absPath, fuzzedString)))
  834. // Headers should always be present even if empty
  835. assert.Contains(t, string(body), fmt.Sprintf("[CONTENT_TYPE] => %s", fuzzedString))
  836. assert.Contains(t, string(body), fmt.Sprintf("[HTTP_FUZZED] => %s", fuzzedString))
  837. }, &testOptions{workerScript: "request-headers.php"})
  838. })
  839. }