Aperçu : route /api/preview en lecture seule et visualiseurs côté client
- GET /api/preview?path= et /api/public/{jeton}/preview : liste blanche d'extensions, inline, nosniff, CSP stricte, texte plafonné à 2 Mo
- Visualiseurs : texte brut, CSV paginé (PapaParse), Markdown sans HTML brut (react-markdown + remark-gfm), code colorisé (highlight.js), PDF natif
- Le HTML s'affiche comme du code, jamais rendu ; RTF/DOC/DOCX hors périmètre
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
fe81055421
commit
d4da3db132
14 files changed
+2378
-39
No files matched your search
+13
-5
@@ -8,6 +8,7 @@
|
||||
// POST /api/meta/tags {"paths":[...],"add":[...],"remove":[...]} tags
|
||||
// POST /api/meta/icon {"paths":[...],"icon":"server"} icône de dossiers ("" : défaut)
|
||||
// GET /api/file?path=a/b.pdf[&inline=1] téléchargement (Range, ETag) ; inline : affichage dans le navigateur si sûr
|
||||
// GET /api/preview?path=a/b.md aperçu en lecture seule (liste blanche, texte plafonné ; voir preview.go)
|
||||
// PUT /api/file?path=a/b.pdf[&conflict=fail|overwrite|rename][&mtime=ms] dépôt en flux
|
||||
// POST /api/folder {"path":"a/b"} création de dossier
|
||||
// POST /api/move {"from":"x","to":"y"} renommage / déplacement
|
||||
@@ -29,7 +30,7 @@
|
||||
// POST /api/shares/revoke-all révocation de tous les liens (administrateur)
|
||||
// GET /api/public/{jeton}[?sub=d] lien de partage (sans authentification)
|
||||
// POST /api/public/{jeton}/unlock mot de passe d'un lien protégé
|
||||
// GET /api/public/{jeton}/file|zip|thumb contenu d'un lien de partage
|
||||
// GET /api/public/{jeton}/file|zip|thumb|preview contenu d'un lien de partage
|
||||
// GET /api/settings / PUT paramètres (écriture : administrateur)
|
||||
// GET /api/logo / PUT (image/png) / DELETE logo 64x64
|
||||
// POST /api/account/password changement du mot de passe (compte local)
|
||||
@@ -63,10 +64,12 @@ type Handler struct {
|
||||
Auth *auth.Auth // nil : pas d'authentification intégrée
|
||||
Accounts *auth.Accounts // nil : pas de comptes (AUTH_MODE=none)
|
||||
|
||||
MaxJSON int64 // taille maximale d'un corps JSON (octets)
|
||||
Mode string // none, local, oidc ou both
|
||||
OIDCName string // libellé du bouton de connexion OIDC
|
||||
Version string
|
||||
MaxJSON int64 // taille maximale d'un corps JSON (octets)
|
||||
// PreviewMaxText : octets de texte servis au plus par /api/preview.
|
||||
PreviewMaxText int64
|
||||
Mode string // none, local, oidc ou both
|
||||
OIDCName string // libellé du bouton de connexion OIDC
|
||||
Version string
|
||||
|
||||
// SecureCookies : cookies de déverrouillage des liens marqués Secure même
|
||||
// en HTTP direct (URL publique en https).
|
||||
@@ -83,6 +86,9 @@ func (h *Handler) Init() *Handler {
|
||||
if h.MaxJSON == 0 {
|
||||
h.MaxJSON = 1 << 20
|
||||
}
|
||||
if h.PreviewMaxText == 0 {
|
||||
h.PreviewMaxText = DefaultPreviewMaxText
|
||||
}
|
||||
h.unlocks = auth.NewLimiter(10, 15*time.Minute)
|
||||
return h
|
||||
}
|
||||
@@ -139,6 +145,7 @@ func (h *Handler) Register(mux *http.ServeMux) {
|
||||
mux.HandleFunc("POST /api/meta/tags", h.editTags)
|
||||
mux.HandleFunc("POST /api/meta/icon", h.setIcon)
|
||||
mux.HandleFunc("GET /api/file", h.download)
|
||||
mux.HandleFunc("GET /api/preview", h.preview)
|
||||
mux.HandleFunc("PUT /api/file", h.upload)
|
||||
mux.HandleFunc("POST /api/folder", h.mkdir)
|
||||
mux.HandleFunc("POST /api/move", h.move)
|
||||
@@ -163,6 +170,7 @@ func (h *Handler) Register(mux *http.ServeMux) {
|
||||
mux.HandleFunc("GET /api/public/{token}/file", h.publicFile)
|
||||
mux.HandleFunc("GET /api/public/{token}/zip", h.publicZip)
|
||||
mux.HandleFunc("GET /api/public/{token}/thumb", h.publicThumb)
|
||||
mux.HandleFunc("GET /api/public/{token}/preview", h.publicPreview)
|
||||
mux.HandleFunc("GET /api/settings", h.readSettings)
|
||||
mux.HandleFunc("PUT /api/settings", h.writeSettings)
|
||||
mux.HandleFunc("GET /api/logo", h.readLogo)
|
||||
|
||||
@@ -0,0 +1,196 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"io/fs"
|
||||
"net/http"
|
||||
"os"
|
||||
"path"
|
||||
"strconv"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/vblogio/upandown/internal/storage"
|
||||
)
|
||||
|
||||
// Aperçu en lecture seule, rendu côté client.
|
||||
//
|
||||
// GET /api/preview?path=x (même authentification que /api/file)
|
||||
// GET /api/public/{jeton}/preview?sub=x (même contrôle que /api/public/{jeton}/file)
|
||||
//
|
||||
// Seules les extensions de la liste blanche sont servies, toujours en
|
||||
// Content-Disposition: inline, avec nosniff et une CSP stricte. Le contenu
|
||||
// texte n'est jamais servi avec un type actif (HTML, XML, JavaScript) : un
|
||||
// fichier .html part en text/plain et s'affiche comme du code. Le texte est
|
||||
// plafonné à Handler.PreviewMaxText ; au-delà, seul le début est envoyé.
|
||||
//
|
||||
// En-têtes de réponse : X-Preview-Kind (text, csv, markdown, code, pdf),
|
||||
// X-Preview-Size (taille réelle du fichier), X-Preview-Truncated (1 si coupé).
|
||||
|
||||
// Genres d'aperçu.
|
||||
const (
|
||||
PreviewText = "text"
|
||||
PreviewCSV = "csv"
|
||||
PreviewMarkdown = "markdown"
|
||||
PreviewCode = "code"
|
||||
PreviewPDF = "pdf"
|
||||
)
|
||||
|
||||
// DefaultPreviewMaxText : plafond par défaut du texte servi en aperçu.
|
||||
const DefaultPreviewMaxText = 2 << 20
|
||||
|
||||
// previewExts : liste blanche des extensions prévisualisables.
|
||||
var previewExts = map[string]string{
|
||||
".txt": PreviewText, ".log": PreviewText, ".rst": PreviewText, ".srt": PreviewText, ".sub": PreviewText,
|
||||
".tex": PreviewText, ".bib": PreviewText, ".nfo": PreviewText,
|
||||
".csv": PreviewCSV, ".tsv": PreviewCSV,
|
||||
".md": PreviewMarkdown, ".markdown": PreviewMarkdown,
|
||||
".pdf": PreviewPDF,
|
||||
}
|
||||
|
||||
// previewNames : fichiers sans extension reconnus par leur nom (en minuscules).
|
||||
var previewNames = map[string]string{
|
||||
"dockerfile": PreviewCode, "containerfile": PreviewCode, "makefile": PreviewCode,
|
||||
"jenkinsfile": PreviewCode, "vagrantfile": PreviewCode,
|
||||
"readme": PreviewText, "license": PreviewText, "changelog": PreviewText,
|
||||
}
|
||||
|
||||
func init() {
|
||||
for _, e := range strings.Fields(`
|
||||
.json .jsonc .js .mjs .cjs .jsx .ts .tsx .yaml .yml .toml .ini .conf .cfg .env .properties
|
||||
.go .py .sh .bash .zsh .ps1 .xml .html .htm .css .scss .less .sql .rs .java .kt .c .h .cpp .hpp
|
||||
.cs .php .rb .lua .tf .hcl .service .gitignore .dockerignore .diff .patch .vue .svelte`) {
|
||||
previewExts[e] = PreviewCode
|
||||
}
|
||||
}
|
||||
|
||||
// PreviewKind renvoie le genre d'aperçu d'un fichier ("" : non prévisualisable).
|
||||
func PreviewKind(name string) string {
|
||||
base := strings.ToLower(path.Base(name))
|
||||
if k, ok := previewNames[base]; ok {
|
||||
return k
|
||||
}
|
||||
// Dockerfile.dev, Containerfile.prod...
|
||||
if strings.HasPrefix(base, "dockerfile.") || strings.HasPrefix(base, "containerfile.") {
|
||||
return PreviewCode
|
||||
}
|
||||
return previewExts[strings.ToLower(path.Ext(base))]
|
||||
}
|
||||
|
||||
// previewType : type MIME servi pour chaque genre. Jamais de type actif.
|
||||
var previewType = map[string]string{
|
||||
PreviewText: "text/plain; charset=utf-8",
|
||||
PreviewCode: "text/plain; charset=utf-8",
|
||||
PreviewCSV: "text/csv; charset=utf-8",
|
||||
PreviewMarkdown: "text/markdown; charset=utf-8",
|
||||
PreviewPDF: "application/pdf",
|
||||
}
|
||||
|
||||
const (
|
||||
// Texte : récupéré par fetch, jamais affiché en navigation directe comme
|
||||
// un document actif ; sandbox et aucune sous-ressource.
|
||||
cspPreviewText = "sandbox; default-src 'none'; frame-ancestors 'none'"
|
||||
// PDF : affiché par la visionneuse du navigateur dans une iframe de
|
||||
// l'application. Pas de sandbox (Chrome refuse alors d'afficher le PDF).
|
||||
cspPreviewPDF = "default-src 'none'; object-src 'self'; frame-ancestors 'self'"
|
||||
)
|
||||
|
||||
func (h *Handler) preview(w http.ResponseWriter, r *http.Request) {
|
||||
u, ok := h.space(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
p := r.URL.Query().Get("path")
|
||||
if PreviewKind(p) == "" {
|
||||
writeErr(w, http.StatusUnsupportedMediaType, "pas d'aperçu pour ce type de fichier")
|
||||
return
|
||||
}
|
||||
f, fi, err := u.Open(p)
|
||||
if err != nil {
|
||||
fail(w, err)
|
||||
return
|
||||
}
|
||||
defer f.Close()
|
||||
h.servePreview(w, r, f, fi)
|
||||
}
|
||||
|
||||
func (h *Handler) publicPreview(w http.ResponseWriter, r *http.Request) {
|
||||
_, st, full, _, ok := h.sharedItem(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
f, fi, err := st.Open(full)
|
||||
if err != nil {
|
||||
fail(w, err)
|
||||
return
|
||||
}
|
||||
defer f.Close()
|
||||
h.servePreview(w, r, f, fi)
|
||||
}
|
||||
|
||||
func (h *Handler) servePreview(w http.ResponseWriter, r *http.Request, f *os.File, fi fs.FileInfo) {
|
||||
name := fi.Name()
|
||||
kind := PreviewKind(name)
|
||||
if kind == "" || fi.IsDir() {
|
||||
writeErr(w, http.StatusUnsupportedMediaType, "pas d'aperçu pour ce type de fichier")
|
||||
return
|
||||
}
|
||||
hd := w.Header()
|
||||
hd.Set("Content-Type", previewType[kind])
|
||||
hd.Set("Content-Disposition", contentDisposition(true, name))
|
||||
hd.Set("X-Content-Type-Options", "nosniff")
|
||||
hd.Set("Cache-Control", "private, no-cache")
|
||||
hd.Set("ETag", storage.ETag(fi))
|
||||
hd.Set("X-Preview-Kind", kind)
|
||||
hd.Set("X-Preview-Size", strconv.FormatInt(fi.Size(), 10))
|
||||
|
||||
if kind == PreviewPDF {
|
||||
hd.Set("Content-Security-Policy", cspPreviewPDF)
|
||||
hd.Set("X-Preview-Truncated", "0")
|
||||
http.ServeContent(w, r, name, fi.ModTime(), f)
|
||||
return
|
||||
}
|
||||
|
||||
hd.Set("Content-Security-Policy", cspPreviewText)
|
||||
max := h.PreviewMaxText
|
||||
if max <= 0 {
|
||||
max = DefaultPreviewMaxText
|
||||
}
|
||||
b, err := io.ReadAll(io.LimitReader(f, max))
|
||||
if err != nil {
|
||||
fail(w, err)
|
||||
return
|
||||
}
|
||||
truncated := fi.Size() > int64(len(b))
|
||||
if truncated {
|
||||
b = trimPartialRune(b)
|
||||
}
|
||||
if bytes.IndexByte(b[:min(len(b), 8192)], 0) >= 0 {
|
||||
hd.Del("Content-Disposition")
|
||||
writeErr(w, http.StatusUnsupportedMediaType, "contenu binaire : pas d'aperçu")
|
||||
return
|
||||
}
|
||||
hd.Set("X-Preview-Truncated", map[bool]string{true: "1", false: "0"}[truncated])
|
||||
// L'ETag désigne le fichier : il reste valable pour l'extrait tant que le
|
||||
// plafond ne change pas. Pas de Range sur un extrait.
|
||||
r.Header.Del("Range")
|
||||
http.ServeContent(w, r, name, fi.ModTime(), bytes.NewReader(b))
|
||||
}
|
||||
|
||||
// trimPartialRune retire un caractère UTF-8 coupé en fin d'extrait.
|
||||
func trimPartialRune(b []byte) []byte {
|
||||
for i := 1; i <= utf8.UTFMax && i <= len(b); i++ {
|
||||
c := b[len(b)-i]
|
||||
if c < 0x80 { // ASCII : rien de coupé
|
||||
return b
|
||||
}
|
||||
if utf8.RuneStart(c) {
|
||||
if r, _ := utf8.DecodeRune(b[len(b)-i:]); r == utf8.RuneError {
|
||||
return b[:len(b)-i]
|
||||
}
|
||||
return b
|
||||
}
|
||||
}
|
||||
return b
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/vblogio/upandown/internal/storage"
|
||||
)
|
||||
|
||||
func TestPreviewKind(t *testing.T) {
|
||||
for name, k := range map[string]string{
|
||||
"a.txt": PreviewText, "x/app.LOG": PreviewText, "d.csv": PreviewCSV, "README.md": PreviewMarkdown,
|
||||
"doc.pdf": PreviewPDF, "c.json": PreviewCode, "i.html": PreviewCode, "k.yaml": PreviewCode,
|
||||
"Dockerfile": PreviewCode, "dockerfile.dev": PreviewCode, "Makefile": PreviewCode,
|
||||
"a.docx": "", "a.rtf": "", "a.doc": "", "a.png": "", "a.exe": "", "noext": "",
|
||||
} {
|
||||
if got := PreviewKind(name); got != k {
|
||||
t.Errorf("PreviewKind(%q) = %q, attendu %q", name, got, k)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPreviewHeadersAndWhitelist(t *testing.T) {
|
||||
f := newFixture(t, nil)
|
||||
s := f.register("alice")
|
||||
want(t, s.put("page.html", "<script>alert(1)</script>"), 200)
|
||||
want(t, s.put("data.csv", "a,b\n1,2\n"), 200)
|
||||
want(t, s.put("note.md", "# titre"), 200)
|
||||
want(t, s.put("doc.pdf", "%PDF-1.4\n"), 200)
|
||||
want(t, s.put("x.docx", "PK"), 200)
|
||||
want(t, s.put("bin.log", "abc\x00def"), 200)
|
||||
|
||||
// Même authentification que le téléchargement.
|
||||
want(t, f.session().get("/api/preview?path=page.html"), 401)
|
||||
|
||||
for p, ct := range map[string]string{
|
||||
"page.html": "text/plain; charset=utf-8",
|
||||
"data.csv": "text/csv; charset=utf-8",
|
||||
"note.md": "text/markdown; charset=utf-8",
|
||||
"doc.pdf": "application/pdf",
|
||||
} {
|
||||
w := s.get("/api/preview?path=" + p)
|
||||
want(t, w, 200)
|
||||
h := w.Header()
|
||||
if h.Get("Content-Type") != ct {
|
||||
t.Errorf("%s : Content-Type %q, attendu %q", p, h.Get("Content-Type"), ct)
|
||||
}
|
||||
if !strings.HasPrefix(h.Get("Content-Disposition"), "inline;") || h.Get("X-Content-Type-Options") != "nosniff" {
|
||||
t.Errorf("%s : en-têtes %v", p, h)
|
||||
}
|
||||
csp := h.Get("Content-Security-Policy")
|
||||
if !strings.Contains(csp, "default-src 'none'") {
|
||||
t.Errorf("%s : CSP %q", p, csp)
|
||||
}
|
||||
if p != "doc.pdf" && !strings.HasPrefix(csp, "sandbox") {
|
||||
t.Errorf("%s : CSP sans sandbox %q", p, csp)
|
||||
}
|
||||
}
|
||||
if b := s.get("/api/preview?path=page.html").Body.String(); b != "<script>alert(1)</script>" {
|
||||
t.Errorf("contenu HTML : %q", b)
|
||||
}
|
||||
want(t, s.get("/api/preview?path=x.docx"), 415)
|
||||
want(t, s.get("/api/preview?path=bin.log"), 415)
|
||||
want(t, s.get("/api/preview?path=absent.txt"), 404)
|
||||
want(t, s.get("/api/preview?path=../../etc/passwd.txt"), 404) // normalisé sous la racine
|
||||
want(t, s.get("/api/preview?path=.accounts.json"), 400)
|
||||
}
|
||||
|
||||
func TestPreviewTextCap(t *testing.T) {
|
||||
f := newFixture(t, nil)
|
||||
f.handler.PreviewMaxText = 10
|
||||
s := f.register("alice")
|
||||
want(t, s.put("court.txt", "court"), 200)
|
||||
want(t, s.put("long.txt", "abcdefghié12345"), 200) // é sur les octets 10-11 : coupé à 9
|
||||
w := s.get("/api/preview?path=court.txt")
|
||||
want(t, w, 200)
|
||||
if w.Body.String() != "court" || w.Header().Get("X-Preview-Truncated") != "0" || w.Header().Get("X-Preview-Size") != "5" {
|
||||
t.Errorf("court : %q %v", w.Body, w.Header())
|
||||
}
|
||||
w = s.get("/api/preview?path=long.txt", "Range", "bytes=0-2")
|
||||
want(t, w, 200) // pas de Range sur l'extrait
|
||||
if w.Body.String() != "abcdefghi" || w.Header().Get("X-Preview-Truncated") != "1" || w.Header().Get("X-Preview-Size") != "16" {
|
||||
t.Errorf("long : %q %v", w.Body, w.Header())
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublicPreview(t *testing.T) {
|
||||
f := newFixture(t, nil)
|
||||
s := f.register("alice")
|
||||
want(t, s.put("dir/a.go", "package a"), 200)
|
||||
want(t, s.put("dir/b.zip", "PK"), 200)
|
||||
sh := decode[storage.Share](t, s.json("POST", "/api/shares", map[string]any{"path": "dir", "days": 1}))
|
||||
v := f.session()
|
||||
w := v.get("/api/public/" + sh.Token + "/preview?sub=a.go")
|
||||
want(t, w, 200)
|
||||
if w.Body.String() != "package a" || w.Header().Get("X-Preview-Kind") != PreviewCode {
|
||||
t.Errorf("public : %q %v", w.Body, w.Header())
|
||||
}
|
||||
want(t, v.get("/api/public/"+sh.Token+"/preview?sub=b.zip"), 415)
|
||||
want(t, v.get("/api/public/nope/preview?sub=a.go"), 404)
|
||||
}
|
||||
Reference in new issue
Block a user