From e380833e60fc0ef4e2ce3efa5507d765e893af43 Mon Sep 17 00:00:00 2001 From: Koala Yeung Date: Fri, 5 Feb 2021 20:20:35 +0800 Subject: [PATCH] session: fix ineffectual code * Rewrite directory index suggestion to prevent ineffectual code. --- session.go | 10 +++++----- session_test.go | 34 +++++++++++++++++++++++++++++++++- 2 files changed, 38 insertions(+), 6 deletions(-) diff --git a/session.go b/session.go index 916ad9a..36191bc 100644 --- a/session.go +++ b/session.go @@ -213,6 +213,11 @@ func (fs *FileSystemRouter) Router() Middleware { fastcgiScriptName, fastcgiPathInfo = matches[1], matches[2] } + // If accessing a directory, try accessing document index file + if strings.HasSuffix(fastcgiScriptName, "/") { + fastcgiScriptName = path.Join(fastcgiScriptName, "index.php") + } + req.Params["PATH_INFO"] = fastcgiPathInfo req.Params["PATH_TRANSLATED"] = filepath.Join(docroot, fastcgiPathInfo) req.Params["SCRIPT_NAME"] = fastcgiScriptName @@ -228,11 +233,6 @@ func (fs *FileSystemRouter) Router() Middleware { } // handle directory index - urlPath := r.URL.Path - if strings.HasSuffix(urlPath, "/") { - urlPath = path.Join(urlPath, "index.php") - } - req.Params["SCRIPT_FILENAME"] = path.Join(fs.DocRoot, urlPath) return inner(client, req) } diff --git a/session_test.go b/session_test.go index 2f1ec99..7ced96c 100644 --- a/session_test.go +++ b/session_test.go @@ -180,7 +180,7 @@ func TestMapFilterRequest(t *testing.T) { } } -func TestFileSystemRouter(t *testing.T) { +func TestFileSystemRouter_PathTraversal(t *testing.T) { fs := &gofast.FileSystemRouter{ DocRoot: "/non-exists/folder/structure", Exts: []string{"php"}, @@ -211,3 +211,35 @@ func TestFileSystemRouter(t *testing.T) { t.Errorf("expected \"%s\", got \"%s\"", want, have) } } + +func TestFileSystemRouter_DirectoryPath(t *testing.T) { + fs := &gofast.FileSystemRouter{ + DocRoot: "/non-exists/folder/structure", + Exts: []string{"php"}, + DirIndex: []string{"index.php"}, + } + + h := gofast.Chain( + gofast.BasicParamsMap, + fs.Router(), + )(func(client gofast.Client, req *gofast.Request) (resp *gofast.ResponsePipe, err error) { + err = fmt.Errorf("SCRIPT_FILENAME=%s", req.Params["SCRIPT_FILENAME"]) + return + }) + + r, err := http.NewRequest("GET", "http://foobar.com/", nil) + if err != nil { + t.Errorf("unexpected error: %s", err) + } + r.URL.Path = "/hello/" + + _, err = h(nil, gofast.NewRequest(r)) + if err == nil { + t.Errorf("expected error, got nil") + return + } + + if want, have := "SCRIPT_FILENAME=/non-exists/folder/structure/hello/index.php", err.Error(); want != have { + t.Errorf("expected \"%s\", got \"%s\"", want, have) + } +}