Add managed Craft addons with secure installation and document editing
This commit is contained in:
1 parent
1afa755d4f
commit
5cb1b463ea
31 files changed
+2274
-15
No files matched your search
+191
@@ -0,0 +1,191 @@
|
||||
package fbhttp
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/filebrowser/filebrowser/v2/internal/addons"
|
||||
"github.com/gorilla/mux"
|
||||
)
|
||||
|
||||
func addonEnabled(d *data, id string) bool {
|
||||
enabled, exists := d.settings.AddonEnabled[id]
|
||||
return !exists || enabled
|
||||
}
|
||||
func addonListHandler(manager *addons.Manager) handleFunc {
|
||||
return withUser(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
|
||||
type entry struct {
|
||||
addons.Status
|
||||
Enabled bool `json:"enabled"`
|
||||
}
|
||||
items := []entry{}
|
||||
for _, tool := range addons.Catalog {
|
||||
items = append(items, entry{manager.Status(tool.ID), addonEnabled(d, tool.ID)})
|
||||
}
|
||||
return renderJSON(w, r, items)
|
||||
})
|
||||
}
|
||||
func addonInstallHandler(manager *addons.Manager) handleFunc {
|
||||
return withAdmin(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
|
||||
id := mux.Vars(r)["addon"]
|
||||
if _, ok := addons.Find(id); !ok {
|
||||
return http.StatusNotFound, nil
|
||||
}
|
||||
if err := manager.Start(id); err != nil {
|
||||
return http.StatusConflict, err
|
||||
}
|
||||
return renderJSON(w, r, manager.Status(id))
|
||||
})
|
||||
}
|
||||
|
||||
var addonToggleHandler = withAdmin(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
|
||||
id := mux.Vars(r)["addon"]
|
||||
if _, ok := addons.Find(id); !ok {
|
||||
return http.StatusNotFound, nil
|
||||
}
|
||||
var payload struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
}
|
||||
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1024)).Decode(&payload); err != nil {
|
||||
return http.StatusBadRequest, err
|
||||
}
|
||||
if d.settings.AddonEnabled == nil {
|
||||
d.settings.AddonEnabled = map[string]bool{}
|
||||
}
|
||||
d.settings.AddonEnabled[id] = payload.Enabled
|
||||
if err := d.store.Settings.Save(d.settings); err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
return renderJSON(w, r, payload)
|
||||
})
|
||||
|
||||
func addonStaticHandler(manager *addons.Manager) handleFunc {
|
||||
return withUser(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
|
||||
vars := mux.Vars(r)
|
||||
id := vars["addon"]
|
||||
if !addonEnabled(d, id) || !d.user.Perm.Download || !d.user.Perm.Modify {
|
||||
return http.StatusForbidden, nil
|
||||
}
|
||||
name := vars["asset"]
|
||||
if name == "" {
|
||||
name = "index.html"
|
||||
}
|
||||
if strings.HasSuffix(name, "/") {
|
||||
return http.StatusNotFound, nil
|
||||
}
|
||||
extension := strings.ToLower(path.Ext(name))
|
||||
types := map[string]string{".html": "text/html; charset=utf-8", ".js": "text/javascript; charset=utf-8", ".wasm": "application/wasm", ".css": "text/css", ".ico": "image/x-icon", ".png": "image/png", ".svg": "image/svg+xml", ".webp": "image/webp", ".jpg": "image/jpeg", ".woff": "font/woff", ".woff2": "font/woff2", ".ttf": "font/ttf", ".otf": "font/otf", ".json": "application/json", ".map": "application/json", ".txt": "text/plain"}
|
||||
contentType, ok := types[extension]
|
||||
if !ok {
|
||||
return http.StatusNotFound, nil
|
||||
}
|
||||
file, err := manager.Open(id, vars["build"], name)
|
||||
if err != nil {
|
||||
return http.StatusNotFound, nil
|
||||
}
|
||||
defer file.Close()
|
||||
if acceptsAddonGzip(r.Header.Get("Accept-Encoding")) {
|
||||
if compressed, e := manager.Open(id, vars["build"], name+".gz"); e == nil {
|
||||
file.Close()
|
||||
file = compressed
|
||||
defer compressed.Close()
|
||||
w.Header().Set("Content-Encoding", "gzip")
|
||||
}
|
||||
}
|
||||
w.Header().Add("Vary", "Accept-Encoding")
|
||||
info, err := file.Stat()
|
||||
if err != nil || !info.Mode().IsRegular() {
|
||||
return http.StatusNotFound, nil
|
||||
}
|
||||
w.Header().Set("Content-Type", contentType)
|
||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
w.Header().Set("Cache-Control", "private, max-age=86400")
|
||||
// Only installed, checksum-verified vendor pages get WASM and framing permissions.
|
||||
w.Header().Set("Content-Security-Policy", `default-src 'self'; script-src 'self' 'unsafe-inline' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data:; connect-src 'self'; worker-src 'self' blob:; media-src 'self' blob:; frame-src 'none'; object-src 'none'; base-uri 'self'; frame-ancestors 'self'`)
|
||||
http.ServeContent(w, r, name, info.ModTime(), file)
|
||||
return 0, nil
|
||||
})
|
||||
}
|
||||
func acceptsAddonGzip(header string) bool {
|
||||
for _, token := range strings.Split(header, ",") {
|
||||
parts := strings.Split(token, ";")
|
||||
if !strings.EqualFold(strings.TrimSpace(parts[0]), "gzip") {
|
||||
continue
|
||||
}
|
||||
for _, option := range parts[1:] {
|
||||
pair := strings.SplitN(strings.TrimSpace(option), "=", 2)
|
||||
if len(pair) == 2 && pair[0] == "q" {
|
||||
quality, err := strconv.ParseFloat(pair[1], 64)
|
||||
return err == nil && quality > 0 && quality <= 1
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Keep executable addon assets outside the user-controlled file namespace, even
|
||||
// when the workspace root includes the program's working directory.
|
||||
func addonPathDenied(d *data, name string, ancestors bool) bool {
|
||||
if d.server.AddonsPath == "" || d.user == nil {
|
||||
return false
|
||||
}
|
||||
realFS, ok := d.user.Fs.(interface{ RealPath(string) (string, error) })
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
actual, err := realFS.RealPath(name)
|
||||
if err != nil {
|
||||
return true
|
||||
}
|
||||
actual = resolveExisting(actual)
|
||||
root := resolveExisting(d.server.AddonsPath)
|
||||
inside := func(parent, child string) bool {
|
||||
rel, e := filepath.Rel(strings.ToLower(parent), strings.ToLower(child))
|
||||
return e == nil && (rel == "." || rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator)))
|
||||
}
|
||||
return inside(root, actual) || (ancestors && inside(actual, root))
|
||||
}
|
||||
func resolveExisting(name string) string {
|
||||
return resolveExistingDepth(name, 0)
|
||||
}
|
||||
func resolveExistingDepth(name string, hops int) string {
|
||||
absolute, err := filepath.Abs(name)
|
||||
if err != nil {
|
||||
return name
|
||||
}
|
||||
tail := []string{}
|
||||
probe := absolute
|
||||
for {
|
||||
resolved, err := filepath.EvalSymlinks(probe)
|
||||
if err == nil {
|
||||
for i := len(tail) - 1; i >= 0; i-- {
|
||||
resolved = filepath.Join(resolved, tail[i])
|
||||
}
|
||||
return resolved
|
||||
}
|
||||
if info, linkErr := os.Lstat(probe); linkErr == nil && info.Mode()&os.ModeSymlink != 0 && hops < 40 {
|
||||
if target, linkErr := os.Readlink(probe); linkErr == nil {
|
||||
if !filepath.IsAbs(target) {
|
||||
target = filepath.Join(filepath.Dir(probe), target)
|
||||
}
|
||||
resolved = resolveExistingDepth(target, hops+1)
|
||||
for i := len(tail) - 1; i >= 0; i-- {
|
||||
resolved = filepath.Join(resolved, tail[i])
|
||||
}
|
||||
return resolved
|
||||
}
|
||||
}
|
||||
parent := filepath.Dir(probe)
|
||||
if parent == probe {
|
||||
return absolute
|
||||
}
|
||||
tail = append(tail, filepath.Base(probe))
|
||||
probe = parent
|
||||
}
|
||||
}
|
||||
+259
@@ -0,0 +1,259 @@
|
||||
package fbhttp
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"path"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/filebrowser/filebrowser/v2/files"
|
||||
"github.com/filebrowser/filebrowser/v2/internal/addons"
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/spf13/afero"
|
||||
)
|
||||
|
||||
const maxCraftDocument = 64 << 20
|
||||
|
||||
// Normal uploads/moves take a shared lock; editor commit/read takes the exclusive
|
||||
// lock so the version check and replacement cannot race our own file API.
|
||||
var craftMutationMu sync.RWMutex
|
||||
var craftRequests = make(chan struct{}, 2)
|
||||
|
||||
func documentETag(data []byte) string { return fmt.Sprintf(`"%x"`, sha256.Sum256(data)) }
|
||||
func readCraftFile(d *data, name string) ([]byte, os.FileInfo, error) {
|
||||
info, err := d.user.Fs.Stat(name)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if !info.Mode().IsRegular() || info.Size() > maxCraftDocument {
|
||||
return nil, nil, errors.New("unsupported document size or type")
|
||||
}
|
||||
f, err := d.user.Fs.Open(name)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
defer f.Close()
|
||||
data, err := io.ReadAll(io.LimitReader(f, maxCraftDocument+1))
|
||||
if len(data) > maxCraftDocument {
|
||||
return nil, nil, errors.New("document exceeds 64 MiB")
|
||||
}
|
||||
return data, info, err
|
||||
}
|
||||
func craftDocumentHandler(manager *addons.Manager, cache FileCache) handleFunc {
|
||||
return withUser(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
|
||||
id := mux.Vars(r)["addon"]
|
||||
tool, ok := addons.Find(id)
|
||||
if !ok {
|
||||
return http.StatusNotFound, nil
|
||||
}
|
||||
if !addonEnabled(d, id) || manager.Status(id).Build == "" || !d.user.Perm.Download || !d.user.Perm.Modify {
|
||||
return http.StatusForbidden, nil
|
||||
}
|
||||
requested := r.URL.Query().Get("path")
|
||||
if requested == "" || strings.ContainsAny(requested, "\\\x00") || !strings.HasPrefix(requested, "/") || path.Clean(requested) != requested {
|
||||
return http.StatusBadRequest, nil
|
||||
}
|
||||
extension := strings.ToLower(path.Ext(requested))
|
||||
if extension != tool.Extension && !(id == "gridcraft" && r.Method == "PUT" && extension == ".pdf") {
|
||||
return http.StatusUnsupportedMediaType, nil
|
||||
}
|
||||
if !d.Check(requested) {
|
||||
return http.StatusForbidden, nil
|
||||
}
|
||||
select {
|
||||
case craftRequests <- struct{}{}:
|
||||
defer func() { <-craftRequests }()
|
||||
default:
|
||||
return http.StatusTooManyRequests, nil
|
||||
}
|
||||
if r.Method == "GET" {
|
||||
craftMutationMu.Lock()
|
||||
data, _, err := readCraftFile(d, requested)
|
||||
craftMutationMu.Unlock()
|
||||
if err != nil {
|
||||
return errToStatus(err), err
|
||||
}
|
||||
if err = validateCraftDocument(extension, data); err != nil {
|
||||
return http.StatusUnprocessableEntity, err
|
||||
}
|
||||
w.Header().Set("ETag", documentETag(data))
|
||||
w.Header().Set("Content-Type", "application/octet-stream")
|
||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
w.Header().Set("Content-Disposition", "attachment")
|
||||
_, err = w.Write(data)
|
||||
return 0, err
|
||||
}
|
||||
var body io.Reader = r.Body
|
||||
if r.Method == "POST" {
|
||||
if !d.user.Perm.Create {
|
||||
return http.StatusForbidden, nil
|
||||
}
|
||||
blank, err := blankCraftDocument(id)
|
||||
if err != nil {
|
||||
return 500, err
|
||||
}
|
||||
body = bytes.NewReader(blank)
|
||||
}
|
||||
if r.Method == "PUT" && r.Header.Get("If-Match") == "" && r.Header.Get("If-None-Match") != "*" {
|
||||
return http.StatusPreconditionRequired, nil
|
||||
}
|
||||
// Stage the complete body before touching the original. A failed upload cannot truncate it.
|
||||
temp, err := afero.TempFile(d.user.Fs, path.Dir(requested), ".filebrowser-craft-")
|
||||
if err != nil {
|
||||
return errToStatus(err), err
|
||||
}
|
||||
tempName := temp.Name()
|
||||
defer d.user.Fs.Remove(tempName)
|
||||
n, err := io.Copy(temp, io.LimitReader(body, maxCraftDocument+1))
|
||||
if err == nil && n > maxCraftDocument {
|
||||
err = errors.New("document exceeds 64 MiB")
|
||||
}
|
||||
if err == nil {
|
||||
err = temp.Sync()
|
||||
}
|
||||
if err != nil {
|
||||
temp.Close()
|
||||
return http.StatusRequestEntityTooLarge, err
|
||||
}
|
||||
if _, err = temp.Seek(0, io.SeekStart); err != nil {
|
||||
temp.Close()
|
||||
return 500, err
|
||||
}
|
||||
payload, err := io.ReadAll(io.LimitReader(temp, maxCraftDocument+1))
|
||||
closeErr := temp.Close()
|
||||
if err != nil {
|
||||
return 500, err
|
||||
}
|
||||
if closeErr != nil {
|
||||
return 500, closeErr
|
||||
}
|
||||
if err = validateCraftDocument(extension, payload); err != nil {
|
||||
return http.StatusUnprocessableEntity, err
|
||||
}
|
||||
craftMutationMu.Lock()
|
||||
defer craftMutationMu.Unlock()
|
||||
current, info, err := readCraftFile(d, requested)
|
||||
exists := err == nil
|
||||
if err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||
return http.StatusConflict, err
|
||||
}
|
||||
create := r.Method == "POST" || r.Header.Get("If-None-Match") == "*"
|
||||
if create {
|
||||
if !d.user.Perm.Create {
|
||||
return 403, nil
|
||||
}
|
||||
if exists {
|
||||
return http.StatusConflict, nil
|
||||
}
|
||||
} else {
|
||||
if !exists || r.Header.Get("If-Match") != documentETag(current) {
|
||||
return http.StatusPreconditionFailed, nil
|
||||
}
|
||||
}
|
||||
mode := d.settings.FileMode
|
||||
if mode == 0 {
|
||||
mode = 0640
|
||||
}
|
||||
if exists {
|
||||
mode = info.Mode().Perm()
|
||||
}
|
||||
if err = d.user.Fs.Chmod(tempName, mode); err != nil {
|
||||
return 500, err
|
||||
}
|
||||
err = d.RunHook(func() error { return d.user.Fs.Rename(tempName, requested) }, "save", requested, "", d.user)
|
||||
if err != nil {
|
||||
return errToStatus(err), err
|
||||
}
|
||||
if cache != nil {
|
||||
if file, e := files.NewFileInfo(&files.FileOptions{Fs: d.user.Fs, Path: requested, Checker: d}); e == nil {
|
||||
if e = delThumbs(r.Context(), cache, file); e != nil {
|
||||
log.Printf("craft thumbnail invalidation: %v", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
w.Header().Set("ETag", documentETag(payload))
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
return 0, nil
|
||||
})
|
||||
}
|
||||
func validateCraftDocument(extension string, data []byte) error {
|
||||
if extension == ".pdf" {
|
||||
if !bytes.HasPrefix(data, []byte("%PDF-")) {
|
||||
return errors.New("invalid PDF")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
reader, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(reader.File) > 4096 {
|
||||
return errors.New("XLSX entry limit")
|
||||
}
|
||||
var total uint64
|
||||
workbook, types := false, false
|
||||
for _, file := range reader.File {
|
||||
total += file.UncompressedSize64
|
||||
if total > 256<<20 || file.UncompressedSize64 > 64<<20 {
|
||||
return errors.New("XLSX expanded size limit")
|
||||
}
|
||||
if file.Name == "xl/workbook.xml" {
|
||||
workbook = true
|
||||
}
|
||||
if file.Name == "[Content_Types].xml" {
|
||||
types = true
|
||||
}
|
||||
}
|
||||
if !workbook || !types {
|
||||
return errors.New("invalid XLSX workbook")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func blankCraftDocument(id string) ([]byte, error) {
|
||||
if id == "pdfcraft" {
|
||||
var b bytes.Buffer
|
||||
b.WriteString("%PDF-1.4\n")
|
||||
offsets := []int{0}
|
||||
for i, obj := range []string{"<< /Type /Catalog /Pages 2 0 R >>", "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 595 842] /Resources << >> >>"} {
|
||||
offsets = append(offsets, b.Len())
|
||||
fmt.Fprintf(&b, "%d 0 obj\n%s\nendobj\n", i+1, obj)
|
||||
}
|
||||
xref := b.Len()
|
||||
fmt.Fprintf(&b, "xref\n0 4\n0000000000 65535 f \n")
|
||||
for _, offset := range offsets[1:] {
|
||||
fmt.Fprintf(&b, "%010d 00000 n \n", offset)
|
||||
}
|
||||
fmt.Fprintf(&b, "trailer\n<< /Size 4 /Root 1 0 R >>\nstartxref\n%d\n%%%%EOF\n", xref)
|
||||
return b.Bytes(), nil
|
||||
}
|
||||
if id != "gridcraft" {
|
||||
return nil, errors.New("unsupported editor")
|
||||
}
|
||||
entries := map[string]string{
|
||||
"[Content_Types].xml": `<?xml version="1.0" encoding="UTF-8"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/><Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/></Types>`,
|
||||
"_rels/.rels": `<?xml version="1.0"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/></Relationships>`,
|
||||
"xl/workbook.xml": `<?xml version="1.0"?><workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets><sheet name="Sheet1" sheetId="1" r:id="rId1"/></sheets></workbook>`,
|
||||
"xl/_rels/workbook.xml.rels": `<?xml version="1.0"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/></Relationships>`,
|
||||
"xl/worksheets/sheet1.xml": `<?xml version="1.0"?><worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><sheetData/></worksheet>`}
|
||||
var b bytes.Buffer
|
||||
writer := zip.NewWriter(&b)
|
||||
for name, content := range entries {
|
||||
f, err := writer.Create(name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, err = f.Write([]byte(content)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
err := writer.Close()
|
||||
return b.Bytes(), err
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
package fbhttp
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"compress/gzip"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"testing/fstest"
|
||||
|
||||
"github.com/filebrowser/filebrowser/v2/files"
|
||||
"github.com/filebrowser/filebrowser/v2/internal/addons"
|
||||
"github.com/filebrowser/filebrowser/v2/settings"
|
||||
"github.com/filebrowser/filebrowser/v2/users"
|
||||
"github.com/gorilla/mux"
|
||||
)
|
||||
|
||||
func installedTestManager(t *testing.T) *addons.Manager {
|
||||
t.Helper()
|
||||
root := t.TempDir()
|
||||
for _, id := range []string{"gridcraft", "pdfcraft"} {
|
||||
dir := filepath.Join(root, id, "versions", "test-123")
|
||||
if err := os.MkdirAll(dir, 0750); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
os.WriteFile(filepath.Join(dir, "index.html"), []byte("index"), 0600)
|
||||
manifest, _ := json.Marshal(addons.Manifest{Version: "test", Build: "test-123"})
|
||||
os.WriteFile(filepath.Join(root, id, "active.json"), manifest, 0600)
|
||||
}
|
||||
return addons.New(root)
|
||||
}
|
||||
func TestCraftSaveConflictPermissionsAndOriginalPreserved(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
manager := installedTestManager(t)
|
||||
initial, _ := blankCraftDocument("gridcraft")
|
||||
os.WriteFile(filepath.Join(root, "book.xlsx"), initial, 0640)
|
||||
key := []byte("craft-test-key")
|
||||
perm := users.Permissions{Download: true, Modify: true, Create: true}
|
||||
store := scopedUserStorage(t, root, perm, key)
|
||||
token := signToken(t, perm, key)
|
||||
handler := handle(craftDocumentHandler(manager, nil), "", store, &settings.Server{})
|
||||
request := func(method, id, name string, body []byte, headers map[string]string) *httptest.ResponseRecorder {
|
||||
r := httptest.NewRequest(method, "/api/craft/"+id+"/document?path="+url.QueryEscape(name), bytes.NewReader(body))
|
||||
r = mux.SetURLVars(r, map[string]string{"addon": id})
|
||||
for k, v := range headers {
|
||||
r.Header.Set(k, v)
|
||||
}
|
||||
r = authorizeTestRequest(r, token)
|
||||
rec := httptest.NewRecorder()
|
||||
handler.ServeHTTP(rec, r)
|
||||
return rec
|
||||
}
|
||||
got := request("GET", "gridcraft", "/book.xlsx", nil, nil)
|
||||
if got.Code != 200 || !bytes.Equal(got.Body.Bytes(), initial) {
|
||||
t.Fatalf("load: %d %s", got.Code, got.Body.String())
|
||||
}
|
||||
tag := got.Header().Get("ETag")
|
||||
if tag == "" {
|
||||
t.Fatal("missing ETag")
|
||||
}
|
||||
if rec := request("PUT", "gridcraft", "/book.xlsx", initial, nil); rec.Code != 428 {
|
||||
t.Fatalf("missing precondition: %d", rec.Code)
|
||||
}
|
||||
if rec := request("PUT", "gridcraft", "/book.xlsx", []byte("broken"), map[string]string{"If-Match": tag}); rec.Code != 422 {
|
||||
t.Fatalf("invalid workbook accepted: %d", rec.Code)
|
||||
}
|
||||
if data, _ := os.ReadFile(filepath.Join(root, "book.xlsx")); !bytes.Equal(data, initial) {
|
||||
t.Fatal("invalid save truncated original")
|
||||
}
|
||||
changed, _ := blankCraftDocument("gridcraft") // Different ZIP ordering/content may be equal, so add a valid ZIP comment.
|
||||
changed = append([]byte(nil), changed...)
|
||||
changed[len(changed)-2] = 1
|
||||
changed = append(changed, 'x')
|
||||
if rec := request("PUT", "gridcraft", "/book.xlsx", changed, map[string]string{"If-Match": tag}); rec.Code != 204 {
|
||||
t.Fatalf("save: %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if rec := request("PUT", "gridcraft", "/book.xlsx", initial, map[string]string{"If-Match": tag}); rec.Code != 412 {
|
||||
t.Fatalf("stale save: %d", rec.Code)
|
||||
}
|
||||
if rec := request("POST", "pdfcraft", "/new.pdf", nil, nil); rec.Code != 204 {
|
||||
t.Fatalf("create PDF: %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if rec := request("POST", "pdfcraft", "/new.pdf", nil, nil); rec.Code != 409 {
|
||||
t.Fatalf("overwrote existing PDF: %d", rec.Code)
|
||||
}
|
||||
if rec := request("GET", "gridcraft", "/../book.xlsx", nil, nil); rec.Code != 400 {
|
||||
t.Fatalf("accepted traversal: %d", rec.Code)
|
||||
}
|
||||
user, _ := store.Users.Get("", false, uint(1))
|
||||
user.Perm.Modify = false
|
||||
if err := store.Users.Save(user); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if rec := request("PUT", "gridcraft", "/book.xlsx", initial, map[string]string{"If-Match": tag}); rec.Code != 403 {
|
||||
t.Fatalf("write without permission: %d", rec.Code)
|
||||
}
|
||||
}
|
||||
func TestAddonAssetsProtectedFromFileAPI(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
addonRoot := filepath.Join(root, "app", "addons")
|
||||
os.MkdirAll(addonRoot, 0750)
|
||||
user := &users.User{Fs: files.NewFs(nil, root, false)}
|
||||
d := &data{server: &settings.Server{AddonsPath: addonRoot}, settings: &settings.Settings{}, user: user}
|
||||
for _, name := range []string{"/app/addons", "/app/addons/gridcraft/code.js"} {
|
||||
if d.CheckRules(name) {
|
||||
t.Fatalf("addon exposed: %s", name)
|
||||
}
|
||||
}
|
||||
if !d.CheckRules("/documents") {
|
||||
t.Fatal("ordinary files denied")
|
||||
}
|
||||
if err := checkDescendants(d, "/app", ""); err == nil {
|
||||
t.Fatal("ancestor deletion allowed")
|
||||
}
|
||||
if err := os.Symlink(addonRoot, filepath.Join(root, "alias")); err == nil {
|
||||
if d.CheckRules("/alias/evil.js") {
|
||||
t.Fatal("addon symlink alias allowed")
|
||||
}
|
||||
}
|
||||
}
|
||||
func TestCraftBlankFormats(t *testing.T) {
|
||||
for id, ext := range map[string]string{"gridcraft": ".xlsx", "pdfcraft": ".pdf"} {
|
||||
data, err := blankCraftDocument(id)
|
||||
if err != nil || validateCraftDocument(ext, data) != nil {
|
||||
t.Fatalf("invalid %s template", id)
|
||||
}
|
||||
if id == "pdfcraft" && !strings.HasSuffix(string(data), "%%EOF\n") {
|
||||
t.Fatal("PDF trailer missing")
|
||||
}
|
||||
}
|
||||
}
|
||||
func TestAddonRoutesAuthMIMECompressionAndDisable(t *testing.T) {
|
||||
manager := installedTestManager(t)
|
||||
root := t.TempDir()
|
||||
key := []byte("addon-route-test")
|
||||
permission := users.Permissions{Download: true, Modify: true}
|
||||
store := scopedUserStorage(t, root, permission, key)
|
||||
handler, err := NewHandler(nil, nil, nil, store, &settings.Server{Root: root, AddonsPath: manager.Root}, fstest.MapFS{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
directory := filepath.Join(manager.Root, "gridcraft", "versions", "test-123")
|
||||
os.WriteFile(filepath.Join(directory, "app.wasm"), []byte("wasm"), 0600)
|
||||
var packed bytes.Buffer
|
||||
zipper := gzip.NewWriter(&packed)
|
||||
zipper.Write([]byte("index"))
|
||||
zipper.Close()
|
||||
os.WriteFile(filepath.Join(directory, "index.html.gz"), packed.Bytes(), 0600)
|
||||
request := func(method, target, token, encoding string) *httptest.ResponseRecorder {
|
||||
r := httptest.NewRequest(method, target, nil)
|
||||
if token != "" {
|
||||
r = authorizeTestRequest(r, token)
|
||||
}
|
||||
r.Header.Set("Accept-Encoding", encoding)
|
||||
rec := httptest.NewRecorder()
|
||||
handler.ServeHTTP(rec, r)
|
||||
return rec
|
||||
}
|
||||
regular := signToken(t, permission, key)
|
||||
if rec := request("GET", "/api/addons", "", " "); rec.Code != 401 {
|
||||
t.Fatalf("anonymous catalog %d", rec.Code)
|
||||
}
|
||||
if rec := request("POST", "/api/addons/gridcraft/install", regular, ""); rec.Code != 403 {
|
||||
t.Fatalf("nonadmin installation %d", rec.Code)
|
||||
}
|
||||
if rec := request("GET", "/addons/gridcraft/test-123/app.wasm", regular, ""); rec.Code != 200 || rec.Header().Get("Content-Type") != "application/wasm" {
|
||||
t.Fatalf("wasm: %d %s", rec.Code, rec.Header().Get("Content-Type"))
|
||||
}
|
||||
compressed := request("GET", "/addons/gridcraft/test-123/index.html", regular, "gzip")
|
||||
if compressed.Code != 200 || compressed.Header().Get("Content-Encoding") != "gzip" || !strings.Contains(compressed.Header().Get("Content-Security-Policy"), "frame-ancestors 'self'") {
|
||||
t.Fatalf("addon page headers: %v", compressed.Header())
|
||||
}
|
||||
reader, err := gzip.NewReader(compressed.Body)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
data, _ := io.ReadAll(reader)
|
||||
reader.Close()
|
||||
if string(data) != "index" {
|
||||
t.Fatal("bad compressed response")
|
||||
}
|
||||
if rec := request("GET", "/addons/gridcraft/test-123/index.html", regular, "gzip;q=0"); rec.Header().Get("Content-Encoding") != "" {
|
||||
t.Fatal("ignored disabled gzip")
|
||||
}
|
||||
configuration, _ := store.Settings.Get()
|
||||
configuration.AddonEnabled = map[string]bool{"gridcraft": false}
|
||||
store.Settings.Save(configuration)
|
||||
if rec := request("GET", "/addons/gridcraft/test-123/index.html", regular, ""); rec.Code != 403 {
|
||||
t.Fatalf("disabled addon accessible %d", rec.Code)
|
||||
}
|
||||
}
|
||||
@@ -46,6 +46,9 @@ func (d *data) Check(path string) bool {
|
||||
// Check, it ignores HideDotfiles: hiding dotfiles is a display preference, so
|
||||
// it must not stop a user from operating on a tree that contains one.
|
||||
func (d *data) CheckRules(path string) bool {
|
||||
if addonPathDenied(d, path, false) {
|
||||
return false
|
||||
}
|
||||
path = d.rulePath(path)
|
||||
|
||||
allow := true
|
||||
|
||||
+26
-1
@@ -3,11 +3,14 @@ package fbhttp
|
||||
import (
|
||||
"io/fs"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/spf13/afero"
|
||||
|
||||
"github.com/filebrowser/filebrowser/v2/files"
|
||||
"github.com/filebrowser/filebrowser/v2/internal/addons"
|
||||
"github.com/filebrowser/filebrowser/v2/settings"
|
||||
"github.com/filebrowser/filebrowser/v2/storage"
|
||||
)
|
||||
@@ -29,6 +32,16 @@ func NewHandler(
|
||||
server.EnableExec = false
|
||||
server.FollowExternalSymlinks = false
|
||||
server.Clean()
|
||||
addonDirectory := server.AddonsPath
|
||||
if addonDirectory == "" {
|
||||
addonDirectory = "addons"
|
||||
}
|
||||
addonRoot, err := filepath.Abs(addonDirectory)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
server.AddonsPath = addonRoot
|
||||
addonManager := addons.New(addonRoot)
|
||||
server.CaseInsensitiveFs = files.CaseInsensitive(afero.NewOsFs(), server.Root)
|
||||
|
||||
r := mux.NewRouter()
|
||||
@@ -41,7 +54,14 @@ func NewHandler(
|
||||
index, static := getStaticHandlers(store, server, assetsFs)
|
||||
|
||||
monkey := func(fn handleFunc, prefix string) http.Handler {
|
||||
return handle(fn, prefix, store, server)
|
||||
handler := handle(fn, prefix, store, server)
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != "GET" && r.Method != "HEAD" && (strings.HasPrefix(prefix, "/api/resources") || strings.HasPrefix(prefix, "/api/tus")) {
|
||||
craftMutationMu.RLock()
|
||||
defer craftMutationMu.RUnlock()
|
||||
}
|
||||
handler.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
r.HandleFunc("/health", healthHandler)
|
||||
@@ -77,6 +97,11 @@ func NewHandler(
|
||||
|
||||
api.Handle("/settings", monkey(settingsGetHandler, "")).Methods("GET")
|
||||
api.Handle("/settings", monkey(settingsPutHandler, "")).Methods("PUT")
|
||||
api.Handle("/addons", monkey(addonListHandler(addonManager), "")).Methods("GET")
|
||||
api.Handle("/addons/{addon}/install", monkey(addonInstallHandler(addonManager), "")).Methods("POST")
|
||||
api.Handle("/addons/{addon}/enabled", monkey(addonToggleHandler, "")).Methods("PUT")
|
||||
api.Handle("/craft/{addon}/document", monkey(craftDocumentHandler(addonManager, fileCache), "")).Methods("GET", "PUT", "POST")
|
||||
r.Handle("/addons/{addon}/{build}/{asset:.*}", monkey(addonStaticHandler(addonManager), "")).Methods("GET", "HEAD")
|
||||
|
||||
api.PathPrefix("/raw").Handler(monkey(rawHandler, "/api/raw")).Methods("GET")
|
||||
api.PathPrefix("/preview/{size}/{path:.*}").
|
||||
|
||||
@@ -281,6 +281,9 @@ func resourcePatchHandler(fileCache FileCache) handleFunc {
|
||||
// delete then recurse through the whole subtree, so a rule denying a descendant
|
||||
// of an allowed directory would be bypassed by operating on the parent instead.
|
||||
func checkDescendants(d *data, src, dst string) error {
|
||||
if addonPathDenied(d, src, true) || (dst != "" && addonPathDenied(d, dst, true)) {
|
||||
return fberrors.ErrPermissionDenied
|
||||
}
|
||||
if len(d.settings.Rules) == 0 && len(d.user.Rules) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user