feat: public Markdown and isolated HTML landing pages (3.2.4)
This commit is contained in:
1 parent
9f777bafbc
commit
3bc62d2b69
50 files changed
+1065
-94
No files matched your search
@@ -110,6 +110,7 @@ func NewHandler(
|
||||
api.PathPrefix("/subtitle").Handler(monkey(subtitleHandler, "/api/subtitle")).Methods("GET")
|
||||
|
||||
public := api.PathPrefix("/public").Subrouter()
|
||||
public.HandleFunc("/landing-shell", publicLandingShell).Methods("GET")
|
||||
public.PathPrefix("/dl").Handler(monkey(publicDlHandler, "/api/public/dl/")).Methods("GET")
|
||||
public.PathPrefix("/share").Handler(monkey(publicShareHandler, "/api/public/share/")).Methods("GET")
|
||||
|
||||
|
||||
+10
-3
@@ -17,6 +17,9 @@ import (
|
||||
var withHashFile = func(fn handleFunc) handleFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
|
||||
id, ifPath := ifPathWithName(r)
|
||||
if !validSharePath(r.URL.Path) {
|
||||
return http.StatusBadRequest, nil
|
||||
}
|
||||
link, err := d.store.Share.GetByHash(id)
|
||||
if err != nil {
|
||||
return errToStatus(err), err
|
||||
@@ -62,14 +65,18 @@ var withHashFile = func(fn handleFunc) handleFunc {
|
||||
|
||||
if file.IsDir {
|
||||
filePath = ifPath
|
||||
} else if ifPath != "/" && ifPath != "." && ifPath != "/"+file.Name {
|
||||
// Keep the legacy /key/original-filename download alias, but never
|
||||
// interpret a suffix on a single-file share as an attachment path.
|
||||
return http.StatusNotFound, nil
|
||||
}
|
||||
|
||||
// set fs root to the shared file/folder. Unless external symlinks are
|
||||
// explicitly allowed, this is a ScopedFs (not a bare BasePathFs) so the
|
||||
// Set fs root to the shared file/folder. Public access always uses a
|
||||
// ScopedFs (not a bare BasePathFs) so the
|
||||
// share is also symlink-confined: a link inside the shared subtree that
|
||||
// points elsewhere in the owner's scope — outside the share — must not be
|
||||
// followed.
|
||||
d.user.Fs = files.NewFs(d.user.Fs, basePath, d.server.FollowExternalSymlinks)
|
||||
d.user.Fs = files.NewScopedFs(d.user.Fs, basePath)
|
||||
|
||||
// the filesystem is now rebased onto basePath, so paths handed to the
|
||||
// rule checker are relative to it. Resolve them back to the user's
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
package fbhttp
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// URL.Path has already been decoded once by net/http. Refuse alternate
|
||||
// separators and residual escapes rather than interpreting a second time.
|
||||
func validSharePath(p string) bool {
|
||||
if strings.ContainsAny(p, "\\%\x00:") {
|
||||
return false
|
||||
}
|
||||
depth := 0
|
||||
for i, part := range strings.Split(p, "/") {
|
||||
if i == 0 {
|
||||
continue
|
||||
}
|
||||
if part == ".." {
|
||||
depth--
|
||||
if depth < 0 {
|
||||
return false
|
||||
}
|
||||
} else if part != "" && part != "." {
|
||||
depth++
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// This empty, credential-free shell is the only place user scripts execute.
|
||||
// A response CSP (not an editable meta tag) survives document.write. The opaque
|
||||
// sandbox origin cannot read cookies, storage, or the File Browser parent.
|
||||
func publicLandingShell(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
w.Header().Set("Referrer-Policy", "no-referrer")
|
||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
w.Header().Set("Content-Security-Policy", "sandbox allow-scripts; default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src blob: data:; media-src blob: data:; font-src data:; connect-src 'none'; frame-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'self'")
|
||||
_, _ = w.Write([]byte(`<!doctype html><meta charset="utf-8"><script>
|
||||
addEventListener('message', function receive(e) {
|
||||
if(e.source !== parent || !e.data || typeof e.data !== 'object' || e.data.type !== 'landing-content' || typeof e.data.html !== 'string') return;
|
||||
removeEventListener('message', receive);
|
||||
document.open(); document.write(e.data.html); document.close();
|
||||
document.addEventListener('click', function(e) {
|
||||
var a=e.target && e.target.closest ? e.target.closest('a[data-landing-link]') : null;
|
||||
if(a){e.preventDefault();parent.postMessage({type:'landing-link',id:a.dataset.landingLink}, '*');}
|
||||
}, true);
|
||||
});
|
||||
parent.postMessage({type:'landing-ready'}, '*');
|
||||
</script>`))
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package fbhttp
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/asdine/storm/v3"
|
||||
"github.com/filebrowser/filebrowser/v2/files"
|
||||
"github.com/filebrowser/filebrowser/v2/settings"
|
||||
"github.com/filebrowser/filebrowser/v2/share"
|
||||
"github.com/filebrowser/filebrowser/v2/storage/bolt"
|
||||
"github.com/filebrowser/filebrowser/v2/users"
|
||||
"github.com/spf13/afero"
|
||||
)
|
||||
|
||||
func TestLandingSharePaths(t *testing.T) {
|
||||
for _, p := range []string{"h/../secret", "h/a/../../secret", "h/%2e%2e/secret", "h/%252e/secret", "h/..\\secret", "h/C:/secret", "h/\x00"} {
|
||||
if validSharePath(p) {
|
||||
t.Errorf("accepted unsafe path %q", p)
|
||||
}
|
||||
}
|
||||
for _, p := range []string{"h", "h/", "h/a/b.png", "h/a/../b.png", "h/фото.png"} {
|
||||
if !validSharePath(p) {
|
||||
t.Errorf("rejected safe path %q", p)
|
||||
}
|
||||
}
|
||||
}
|
||||
func TestLandingShellIsolation(t *testing.T) {
|
||||
w := httptest.NewRecorder()
|
||||
publicLandingShell(w, httptest.NewRequest("GET", "/api/public/landing-shell", nil))
|
||||
csp := w.Header().Get("Content-Security-Policy")
|
||||
for _, rule := range []string{"sandbox allow-scripts;", "default-src 'none'", "connect-src 'none'", "frame-src 'none'", "form-action 'none'", "frame-ancestors 'self'"} {
|
||||
if !strings.Contains(csp, rule) {
|
||||
t.Errorf("missing %q in CSP %q", rule, csp)
|
||||
}
|
||||
}
|
||||
if strings.Contains(csp, "allow-same-origin") {
|
||||
t.Fatal("shell can access session origin")
|
||||
}
|
||||
if strings.Contains(w.Body.String(), "token") {
|
||||
t.Fatal("shell contains credentials")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublicLandingAttachmentBoundaries(t *testing.T) {
|
||||
scope := t.TempDir()
|
||||
if err := os.MkdirAll(filepath.Join(scope, "site", "images"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for name, body := range map[string]string{"site/page.md": "# Landing", "site/images/a.svg": "<svg/>", "single.md": "# Single", "secret.txt": "private"} {
|
||||
if err := os.WriteFile(filepath.Join(scope, filepath.FromSlash(name)), []byte(body), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
db, err := storm.Open(filepath.Join(t.TempDir(), "db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
st, err := bolt.NewStorage(db)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := st.Users.Save(&users.User{Username: "owner", Password: "unused", Perm: users.Permissions{Share: true, Download: true}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := st.Settings.Save(&settings.Settings{Key: []byte("key")}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
st.Users = &customFSUser{Store: st.Users, fs: files.NewScopedFs(afero.NewOsFs(), scope)}
|
||||
for _, link := range []*share.Link{{Hash: "folder", UserID: 1, Path: "/site"}, {Hash: "single", UserID: 1, Path: "/single.md"}} {
|
||||
if err := st.Share.Save(link); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
path string
|
||||
status int
|
||||
}{
|
||||
{"folder/page.md", 200}, {"folder/images/a.svg", 200}, {"folder/../secret.txt", 400},
|
||||
{"folder/%2e%2e/secret.txt", 400}, {"folder/%252e%252e/secret.txt", 400}, {"folder/..\\secret.txt", 400},
|
||||
{"single/", 200}, {"single/single.md", 200}, {"single/secret.txt", 404},
|
||||
} {
|
||||
for _, handler := range []handleFunc{publicDlHandler, publicShareHandler} {
|
||||
req := newHTTPRequest(t, func(r *http.Request) { r.URL.Path = tc.path })
|
||||
recorder := httptest.NewRecorder()
|
||||
handle(handler, "", st, &settings.Server{}).ServeHTTP(recorder, req)
|
||||
if recorder.Code != tc.status {
|
||||
t.Errorf("%s: got %d, want %d: %s", tc.path, recorder.Code, tc.status, recorder.Body.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+15
-75
@@ -126,83 +126,23 @@ func TestPublicShareSymlinkListingOmitsEscapingLink(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// With Server.FollowExternalSymlinks enabled (the opt-in for issue #5998), a
|
||||
// symlink inside a public share that points outside it is followed: the file
|
||||
// behind it downloads and the link shows up in the share listing. This is the
|
||||
// inverse of TestPublicShareSymlinkDescendantDisclosure / ...ListingOmitsEscapingLink.
|
||||
func TestPublicShareSymlinkFollowedWhenEnabled(t *testing.T) {
|
||||
scope := t.TempDir()
|
||||
if err := os.MkdirAll(filepath.Join(scope, "shared"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Join(scope, "outside"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(scope, "outside", "data.txt"), []byte("payload"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Symlink(filepath.Join(scope, "outside"), filepath.Join(scope, "shared", "link")); err != nil {
|
||||
t.Skipf("cannot create symlink on this platform: %v", err)
|
||||
}
|
||||
|
||||
db, err := storm.Open(filepath.Join(t.TempDir(), "db"))
|
||||
// Public shares remain confined even when an owner filesystem follows links.
|
||||
func TestPublicShareSymlinkConfinedWhenEnabled(t *testing.T) {
|
||||
st := symlinkShareStorage(t)
|
||||
owner := st.Users.(*customFSUser)
|
||||
root, err := files.BasePath(owner.fs).RealPath("/")
|
||||
if err != nil {
|
||||
t.Fatalf("failed to open db: %v", err)
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = db.Close() })
|
||||
|
||||
st, err := bolt.NewStorage(db)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to get storage: %v", err)
|
||||
}
|
||||
if err := st.Share.Save(&share.Link{Hash: "h", UserID: 1, Path: "/shared"}); err != nil {
|
||||
t.Fatalf("failed to save share: %v", err)
|
||||
}
|
||||
if err := st.Users.Save(&users.User{
|
||||
Username: "username",
|
||||
Password: "pw",
|
||||
Perm: users.Permissions{Share: true, Download: true},
|
||||
}); err != nil {
|
||||
t.Fatalf("failed to save user: %v", err)
|
||||
}
|
||||
if err := st.Settings.Save(&settings.Settings{Key: []byte("key")}); err != nil {
|
||||
t.Fatalf("failed to save settings: %v", err)
|
||||
}
|
||||
// Follow-external mode: the user filesystem is a bare BasePathFs.
|
||||
st.Users = &customFSUser{
|
||||
Store: st.Users,
|
||||
fs: files.NewFs(afero.NewOsFs(), scope, true),
|
||||
followExternal: true,
|
||||
}
|
||||
|
||||
srv := &settings.Server{FollowExternalSymlinks: true}
|
||||
|
||||
// The file behind the symlink downloads.
|
||||
req := newHTTPRequest(t, func(r *http.Request) { r.URL.Path = "h/link/data.txt" })
|
||||
recorder := httptest.NewRecorder()
|
||||
handle(publicDlHandler, "", st, srv).ServeHTTP(recorder, req)
|
||||
result := recorder.Result()
|
||||
defer result.Body.Close()
|
||||
body, _ := io.ReadAll(result.Body)
|
||||
if result.StatusCode != http.StatusOK {
|
||||
t.Fatalf("expected to download file behind followed symlink, got status=%d body=%q", result.StatusCode, string(body))
|
||||
}
|
||||
if !strings.Contains(string(body), "payload") {
|
||||
t.Fatalf("expected payload content, got %q", string(body))
|
||||
}
|
||||
|
||||
// The link shows up in the share root listing.
|
||||
req = newHTTPRequest(t, func(r *http.Request) { r.URL.Path = "h/" })
|
||||
recorder = httptest.NewRecorder()
|
||||
handle(publicShareHandler, "", st, srv).ServeHTTP(recorder, req)
|
||||
result = recorder.Result()
|
||||
defer result.Body.Close()
|
||||
body, _ = io.ReadAll(result.Body)
|
||||
if result.StatusCode != http.StatusOK {
|
||||
t.Fatalf("share root listing failed: status=%d body=%q", result.StatusCode, string(body))
|
||||
}
|
||||
if !strings.Contains(string(body), "\"link\"") {
|
||||
t.Fatalf("expected followed symlink to appear in listing: %s", string(body))
|
||||
owner.fs = files.NewFs(afero.NewOsFs(), root, true)
|
||||
owner.followExternal = true
|
||||
for _, handler := range []handleFunc{publicDlHandler, publicShareHandler} {
|
||||
req := newHTTPRequest(t, func(r *http.Request) { r.URL.Path = "h/link/secret.txt" })
|
||||
recorder := httptest.NewRecorder()
|
||||
handle(handler, "", st, &settings.Server{FollowExternalSymlinks: true}).ServeHTTP(recorder, req)
|
||||
if recorder.Code == http.StatusOK {
|
||||
t.Fatal("public share followed escaping symlink")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -35,6 +35,7 @@ func TestPublicShareHandlerAuthentication(t *testing.T) {
|
||||
downloadPerm: true,
|
||||
expectedStatusCode: 200,
|
||||
},
|
||||
"Expired share, 404": {share: &share.Link{Hash: "h", UserID: 1, Expire: 1}, req: newHTTPRequest(t), sharePerm: true, downloadPerm: true, expectedStatusCode: 404},
|
||||
"Private share, no auth provided, 401": {
|
||||
share: &share.Link{Hash: "h", UserID: 1, PasswordHash: passwordBcrypt, Token: "123"},
|
||||
req: newHTTPRequest(t),
|
||||
|
||||
Reference in new issue
Block a user