1
package fastcgi
2
3
import (
4
+ "context"
5
+ "net"
6
+ "net/http"
7
"strings"
8
"testing"
9
11
"github.com/stretchr/testify/require"
12
13
"github.com/caddyserver/caddy/v2"
14
+ "github.com/caddyserver/caddy/v2/modules/caddyhttp"
15
)
16
17
func TestProvisionSplitPath(t *testing.T) {
359
assert.Equalf(t, -1, tr.splitPos(p), "payload %q must not be detected as .php", p)
360
}
361
}
362
+
363
+func TestBuildEnvServerAddr(t *testing.T) {
364
+ testCases := []struct {
365
+ name string
366
+ localAddr net.Addr
367
+ envVars map[string]string
368
+ expectedAddr string
369
+ expectExists bool
370
+ }{
371
+ {
372
+ name: "IPv4 TCP listener",
373
+ localAddr: &net.TCPAddr{IP: net.ParseIP("10.0.0.12"), Port: 80},
374
+ expectedAddr: "10.0.0.12",
375
+ expectExists: true,
376
+ },
377
+ {
378
+ name: "IPv6 TCP listener",
379
+ localAddr: &net.TCPAddr{IP: net.ParseIP("2001:db8::1"), Port: 443},
380
+ expectedAddr: "2001:db8::1",
381
+ expectExists: true,
382
+ },
383
+ {
384
+ name: "Missing local address context",
385
+ localAddr: nil,
386
+ expectExists: false,
387
+ },
388
+ {
389
+ name: "Unix listener",
390
+ localAddr: &net.UnixAddr{Name: "/var/run/caddy.sock", Net: "unix"},
391
+ expectExists: false,
392
+ },
393
+ {
394
+ name: "Explicitly configured SERVER_ADDR override",
395
+ localAddr: &net.TCPAddr{IP: net.ParseIP("10.0.0.12"), Port: 80},
396
+ envVars: map[string]string{"SERVER_ADDR": "192.168.1.100"},
397
+ expectedAddr: "192.168.1.100",
398
+ expectExists: true,
399
+ },
400
+ }
401
+
402
+ for _, tc := range testCases {
403
+ t.Run(tc.name, func(t *testing.T) {
404
+ tr := Transport{
405
+ Root: "/var/www",
406
+ EnvVars: tc.envVars,
407
+ }
408
+ err := tr.Provision(caddy.Context{})
409
+ require.NoError(t, err)
410
+
411
+ req, err := http.NewRequest(http.MethodGet, "http://localhost/index.php", nil)
412
+ require.NoError(t, err)
413
+
414
+ req = req.WithContext(context.WithValue(req.Context(), caddyhttp.OriginalRequestCtxKey, *req))
415
+ repl := caddy.NewReplacer()
416
+ req = req.WithContext(context.WithValue(req.Context(), caddy.ReplacerCtxKey, repl))
417
+
418
+ if tc.localAddr != nil {
419
+ req = req.WithContext(context.WithValue(req.Context(), http.LocalAddrContextKey, tc.localAddr))
420
+ }
421
+
422
+ env, err := tr.buildEnv(req)
423
+ require.NoError(t, err)
424
+
425
+ val, exists := env["SERVER_ADDR"]
426
+ assert.Equal(t, tc.expectExists, exists)
427
+ if tc.expectExists {
428
+ assert.Equal(t, tc.expectedAddr, val)
429
+ }
430
+ })
431
+ }
432
+}
433
+