Up And Down : première version

This commit is contained in:
cedric committed 2026-11-19 10:30:47 +01:00
commit 89c5430308
76 files changed
+20730

No files matched your search

+88
View File
@@ -0,0 +1,88 @@
package api
import (
"log/slog"
"net/http"
"github.com/vblogio/upandown/internal/auth"
)
func (h *Handler) adminUsers(w http.ResponseWriter, r *http.Request) {
if !h.admin(w, r) {
return
}
w.Header().Set("Cache-Control", "no-store")
writeJSON(w, http.StatusOK, h.Accounts.List())
}
func (h *Handler) adminCreateUser(w http.ResponseWriter, r *http.Request) {
if !h.admin(w, r) {
return
}
var req struct {
Username string `json:"username"`
Name string `json:"name"`
Email string `json:"email"`
Password string `json:"password"`
Role string `json:"role"`
}
if !h.decode(w, r, &req) {
return
}
acc, err := h.Accounts.CreateLocal(auth.NewAccount{Username: req.Username, Name: req.Name, Email: req.Email,
Password: req.Password, Role: req.Role, Status: auth.StatusActive})
if err != nil {
accountErr(w, err)
return
}
slog.Info("compte créé", "user", acc.ID, "by", userID(r))
writeJSON(w, http.StatusCreated, acc.Info())
}
func (h *Handler) adminPatchUser(w http.ResponseWriter, r *http.Request) {
if !h.admin(w, r) {
return
}
var req struct {
Name *string `json:"name"`
Email *string `json:"email"`
Role *string `json:"role"`
Status *string `json:"status"`
Password *string `json:"password"`
}
if !h.decode(w, r, &req) {
return
}
id := r.PathValue("id")
acc, err := h.Accounts.Update(id, auth.Patch{Name: req.Name, Email: req.Email, Role: req.Role,
Status: req.Status, Password: req.Password})
if err != nil {
accountErr(w, err)
return
}
slog.Info("compte modifié", "user", id, "by", userID(r))
writeJSON(w, http.StatusOK, acc.Info())
}
func (h *Handler) adminDeleteUser(w http.ResponseWriter, r *http.Request) {
if !h.admin(w, r) {
return
}
id := r.PathValue("id")
if id == userID(r) {
writeErr(w, http.StatusBadRequest, "vous ne pouvez pas supprimer votre propre compte")
return
}
if err := h.Accounts.Delete(id); err != nil {
accountErr(w, err)
return
}
if h.OnUserRemoved != nil {
h.OnUserRemoved(id)
}
if err := h.Spaces.RetireUser(id); err != nil {
slog.Warn("espace personnel non mis de côté", "user", id, "err", err)
}
slog.Info("compte supprimé", "user", id, "by", userID(r))
w.WriteHeader(http.StatusNoContent)
}
+241
View File
@@ -0,0 +1,241 @@
// Package api expose les fichiers en REST/JSON.
//
// GET /api/me session, fournisseurs et réglages publics (sans authentification)
// GET /api/list?path=dir[&details=1] contenu d'un dossier (details : vue Galerie)
// GET /api/search?q=texte[&tag=t][&fav=true][&details=1] recherche (noms, tags, texte des fichiers)
// GET /api/tags tags utilisés et nombre d'éléments
// POST /api/meta/favorite {"paths":[...],"favorite":true} favoris
// 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
// 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
// POST /api/move-many {"paths":[...],"dir":"d"} déplacement multiple
// POST /api/copy {"from":"x","to":"y"} duplication (fichier ou dossier)
// DELETE /api/entry?path=x[&recursive=true] mise à la poubelle (suppression définitive
// dans .poubelle ; path=.poubelle : la vide)
// POST /api/trash/restore {"paths":[...]} restauration depuis la poubelle
// GET /api/thumb?path=x miniature d'une image
// GET /api/zip?path=x / POST (formulaire paths=[...]) archive ZIP en flux
// GET /api/hash?path=x empreinte SHA-256 d'un fichier
// GET /api/history?path=x versions d'un fichier
// GET /api/history/version?path=x&id=v contenu d'une version
// POST /api/history/snapshot {"path"} version du contenu courant
// POST /api/history/restore {"path","id"} restauration
// GET /api/shares[?path=x] liens de partage (d'un élément ou tous)
// POST /api/shares {"path","days","password"} nouveau lien (days 0 : sans expiration)
// DELETE /api/shares?id=x révocation d'un lien
// 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/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)
// PATCH /api/account nom et e-mail (compte local)
// GET|POST /api/admin/users, PATCH|DELETE /api/admin/users/{id} comptes (administrateur)
//
// Les chemins sont vus par l'utilisateur connecté (storage.Space) : l'arborescence
// commune, plus ".perso/..." (son espace personnel), ".favoris" (ses favoris,
// liens symboliques vers les originaux ; DELETE .favoris/x retire le lien) et
// ".poubelle" (éléments supprimés, de l'arborescence commune et de son espace).
package api
import (
"encoding/json"
"errors"
"io"
"log/slog"
"net/http"
"strings"
"time"
"github.com/vblogio/upandown/internal/auth"
"github.com/vblogio/upandown/internal/storage"
)
// Handler regroupe les routes de l'API.
type Handler struct {
Store *storage.Store // arborescence commune : paramètres, logo
Spaces *storage.Spaces // fichiers : arborescence commune, espaces personnels, favoris
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
// SecureCookies : cookies de déverrouillage des liens marqués Secure même
// en HTTP direct (URL publique en https).
SecureCookies bool
// OnUserRemoved est appelé après la suppression d'un compte (jetons à révoquer).
OnUserRemoved func(id string)
unlocks *auth.Limiter
}
// Init prépare les limiteurs internes ; à appeler avant Register.
func (h *Handler) Init() *Handler {
if h.MaxJSON == 0 {
h.MaxJSON = 1 << 20
}
h.unlocks = auth.NewLimiter(10, 15*time.Minute)
return h
}
// userID identifie l'utilisateur d'une requête : identifiant de son compte,
// ou LocalUser sans authentification intégrée.
func userID(r *http.Request) string {
if u := auth.UserFrom(r.Context()); u != nil && u.ID != "" {
return u.ID
}
return storage.LocalUser
}
// UserID est la fonction d'identification utilisée aussi par les jetons.
func UserID(r *http.Request) string { return userID(r) }
// isAdmin : sans authentification intégrée (AUTH_MODE=none), tout le monde
// administre, le contrôle d'accès étant alors celui du reverse proxy. Sinon,
// il faut une session de rôle administrateur.
func (h *Handler) isAdmin(r *http.Request) bool {
if h.Mode == "none" {
return true
}
u := auth.UserFrom(r.Context())
return u != nil && u.Role == auth.RoleAdmin
}
// space renvoie la vue de l'utilisateur de la requête (espace personnel et favoris).
func (h *Handler) space(w http.ResponseWriter, r *http.Request) (*storage.Space, bool) {
u, err := h.Spaces.For(userID(r), h.isAdmin(r))
if err != nil {
fail(w, err)
return nil, false
}
return u, true
}
// admin refuse les requêtes des non-administrateurs.
func (h *Handler) admin(w http.ResponseWriter, r *http.Request) bool {
if !h.isAdmin(r) {
writeErr(w, http.StatusForbidden, "réservé aux administrateurs")
return false
}
return true
}
// Register enregistre les routes sur mux (motifs Go 1.22+).
func (h *Handler) Register(mux *http.ServeMux) {
mux.HandleFunc("GET /api/me", h.me)
mux.HandleFunc("GET /api/list", h.list)
mux.HandleFunc("GET /api/search", h.search)
mux.HandleFunc("GET /api/tags", h.tags)
mux.HandleFunc("POST /api/meta/favorite", h.setFavorite)
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("PUT /api/file", h.upload)
mux.HandleFunc("POST /api/folder", h.mkdir)
mux.HandleFunc("POST /api/move", h.move)
mux.HandleFunc("POST /api/move-many", h.moveMany)
mux.HandleFunc("POST /api/copy", h.copy)
mux.HandleFunc("DELETE /api/entry", h.delete)
mux.HandleFunc("POST /api/trash/restore", h.restoreTrash)
mux.HandleFunc("GET /api/thumb", h.thumb)
mux.HandleFunc("GET /api/zip", h.zip)
mux.HandleFunc("POST /api/zip", h.zip)
mux.HandleFunc("GET /api/hash", h.hash)
mux.HandleFunc("GET /api/history", h.history)
mux.HandleFunc("GET /api/history/version", h.readVersion)
mux.HandleFunc("POST /api/history/snapshot", h.snapshot)
mux.HandleFunc("POST /api/history/restore", h.restore)
mux.HandleFunc("GET /api/shares", h.shares)
mux.HandleFunc("POST /api/shares", h.createShare)
mux.HandleFunc("DELETE /api/shares", h.revokeShare)
mux.HandleFunc("POST /api/shares/revoke-all", h.revokeAllShares)
mux.HandleFunc("GET /api/public/{token}", h.publicInfo)
mux.HandleFunc("POST /api/public/{token}/unlock", h.publicUnlock)
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/settings", h.readSettings)
mux.HandleFunc("PUT /api/settings", h.writeSettings)
mux.HandleFunc("GET /api/logo", h.readLogo)
mux.HandleFunc("PUT /api/logo", h.writeLogo)
mux.HandleFunc("DELETE /api/logo", h.deleteLogo)
if h.Accounts != nil {
mux.HandleFunc("POST /api/account/password", h.changePassword)
mux.HandleFunc("PATCH /api/account", h.patchAccount)
mux.HandleFunc("GET /api/admin/users", h.adminUsers)
mux.HandleFunc("POST /api/admin/users", h.adminCreateUser)
mux.HandleFunc("PATCH /api/admin/users/{id}", h.adminPatchUser)
mux.HandleFunc("DELETE /api/admin/users/{id}", h.adminDeleteUser)
}
mux.HandleFunc("/api/", func(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusNotFound, "route inconnue")
})
}
func writeJSON(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(v)
}
func writeErr(w http.ResponseWriter, status int, msg string) {
writeJSON(w, status, map[string]string{"error": msg})
}
// fail traduit une erreur du Store en code HTTP.
func fail(w http.ResponseWriter, err error) {
var tooBig *http.MaxBytesError
switch {
case errors.Is(err, storage.ErrNotFound):
writeErr(w, http.StatusNotFound, err.Error())
case errors.Is(err, storage.ErrExists), errors.Is(err, storage.ErrNotEmpty):
writeErr(w, http.StatusConflict, err.Error())
case errors.Is(err, storage.ErrConflict):
writeErr(w, http.StatusPreconditionFailed, err.Error())
case errors.Is(err, storage.ErrInvalidPath), errors.Is(err, storage.ErrInvalidImage):
writeErr(w, http.StatusBadRequest, err.Error())
case errors.Is(err, storage.ErrForbidden):
writeErr(w, http.StatusForbidden, err.Error())
case errors.Is(err, storage.ErrQuota):
writeErr(w, http.StatusInsufficientStorage, err.Error())
case errors.Is(err, storage.ErrTooLarge), errors.As(err, &tooBig):
writeErr(w, http.StatusRequestEntityTooLarge, "fichier trop volumineux")
default:
slog.Error("erreur interne", "err", err)
writeErr(w, http.StatusInternalServerError, "erreur interne")
}
}
func (h *Handler) readBody(w http.ResponseWriter, r *http.Request) ([]byte, error) {
return io.ReadAll(http.MaxBytesReader(w, r.Body, h.MaxJSON))
}
func (h *Handler) decode(w http.ResponseWriter, r *http.Request, v any) bool {
b, err := h.readBody(w, r)
if err == nil {
err = json.Unmarshal(b, v)
}
if err != nil {
writeErr(w, http.StatusBadRequest, "requête JSON invalide")
return false
}
return true
}
func wantDetails(r *http.Request) bool {
v := r.URL.Query().Get("details")
return v == "1" || v == "true"
}
func secure(r *http.Request) bool {
return r.TLS != nil || strings.EqualFold(r.Header.Get("X-Forwarded-Proto"), "https")
}
+646
View File
@@ -0,0 +1,646 @@
package api
import (
"archive/zip"
"bytes"
"encoding/json"
"image"
"image/color"
"image/png"
"io"
"net/http"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/vblogio/upandown/internal/auth"
"github.com/vblogio/upandown/internal/storage"
"github.com/vblogio/upandown/internal/tokens"
)
// fixture assemble le même graphe que cmd/server (mode local), sans ouvrir de port.
type fixture struct {
root string
t *testing.T
h http.Handler
handler *Handler
accounts *auth.Accounts
tokens *tokens.Store
spaces *storage.Spaces
}
func newFixture(t *testing.T, mutate func(*storage.Store, *storage.Spaces)) *fixture {
t.Helper()
dir := t.TempDir()
store, err := storage.New(dir)
if err != nil {
t.Fatal(err)
}
spaces := storage.NewSpaces(store)
if mutate != nil {
mutate(store, spaces)
}
accounts, err := auth.OpenAccounts(dir)
if err != nil {
t.Fatal(err)
}
h := (&Handler{Store: store, Spaces: spaces, Mode: "local", Accounts: accounts}).Init()
a := auth.New(&auth.Auth{
Accounts: accounts, Sessions: auth.NewSessions([]byte("0123456789abcdef0123456789abcdef"), time.Hour, false),
Local: true,
Registration: func() string {
st, _ := store.ReadSettings()
return st.Registration
},
})
h.Auth = a
mux := http.NewServeMux()
a.Register(mux)
h.Register(mux)
tokenStore, err := tokens.Open(dir)
if err != nil {
t.Fatal(err)
}
ts := &tokens.Server{Store: tokenStore, UserID: UserID, Resolve: func(id string) (*auth.User, bool) {
acc, ok := accounts.Get(id)
if !ok || acc.Status != auth.StatusActive {
return nil, false
}
u := acc.User()
return &u, true
}}
ts.Register(mux)
public := func(p string) bool {
return strings.HasPrefix(p, "/api/public/") || p == "/api/me" || p == "/api/logo"
}
return &fixture{root: dir, t: t, h: ts.Middleware(a.Middleware(mux, public), mux), handler: h, accounts: accounts, tokens: tokenStore, spaces: spaces}
}
type session struct {
f *fixture
cookies map[string]*http.Cookie
bearer string
}
func (f *fixture) session() *session { return &session{f: f, cookies: map[string]*http.Cookie{}} }
func (s *session) do(method, target string, body io.Reader, hdr ...string) *httptest.ResponseRecorder {
s.f.t.Helper()
r := httptest.NewRequest(method, target, body)
for i := 0; i+1 < len(hdr); i += 2 {
r.Header.Set(hdr[i], hdr[i+1])
}
for _, c := range s.cookies {
r.AddCookie(c)
}
if s.bearer != "" {
r.Header.Set("Authorization", "Bearer "+s.bearer)
}
w := httptest.NewRecorder()
s.f.h.ServeHTTP(w, r)
for _, c := range w.Result().Cookies() {
if c.MaxAge < 0 {
delete(s.cookies, c.Name)
} else {
s.cookies[c.Name] = c
}
}
return w
}
func (s *session) json(method, target string, v any) *httptest.ResponseRecorder {
b, _ := json.Marshal(v)
return s.do(method, target, bytes.NewReader(b), "Content-Type", "application/json")
}
func (s *session) put(path, content string, query ...string) *httptest.ResponseRecorder {
q := ""
for _, x := range query {
q += "&" + x
}
return s.do("PUT", "/api/file?path="+url.QueryEscape(path)+q, strings.NewReader(content))
}
func (s *session) get(target string, hdr ...string) *httptest.ResponseRecorder {
return s.do("GET", target, nil, hdr...)
}
func decode[T any](t *testing.T, w *httptest.ResponseRecorder) T {
t.Helper()
var v T
if err := json.Unmarshal(w.Body.Bytes(), &v); err != nil {
t.Fatalf("JSON illisible (%d) : %v : %s", w.Code, err, w.Body)
}
return v
}
func want(t *testing.T, w *httptest.ResponseRecorder, code int) {
t.Helper()
if w.Code != code {
t.Fatalf("code %d (attendu %d) : %s", w.Code, code, strings.TrimSpace(w.Body.String()))
}
}
// register crée un compte par l'inscription et renvoie sa session.
func (f *fixture) register(name string) *session {
f.t.Helper()
s := f.session()
w := s.json("POST", "/auth/local/register", map[string]string{"username": name, "password": "mot-de-passe-" + name})
if w.Code != 201 && w.Code != 202 {
f.t.Fatalf("inscription de %s : %d %s", name, w.Code, w.Body)
}
return s
}
func (f *fixture) login(name string) *session {
f.t.Helper()
s := f.session()
want(f.t, s.json("POST", "/auth/local/login", map[string]string{"username": name, "password": "mot-de-passe-" + name}), 200)
return s
}
func makePNG(t *testing.T, w, h int) string {
t.Helper()
img := image.NewRGBA(image.Rect(0, 0, w, h))
for y := 0; y < h; y++ {
for x := 0; x < w; x++ {
img.Set(x, y, color.RGBA{uint8(x), uint8(y), 99, 255})
}
}
var buf bytes.Buffer
if err := png.Encode(&buf, img); err != nil {
t.Fatal(err)
}
return buf.String()
}
func TestAnonymousAndSetup(t *testing.T) {
f := newFixture(t, nil)
anon := f.session()
want(t, anon.get("/api/list?path="), 401)
want(t, anon.put("a.txt", "x"), 401)
me := decode[meResponse](t, anon.get("/api/me"))
if !me.Setup || me.User != nil || !me.Local || me.Registration != "closed" {
t.Errorf("/api/me avant installation : %+v", me)
}
admin := f.register("alice")
me = decode[meResponse](t, admin.get("/api/me"))
if me.Setup || me.User == nil || me.User.ID != "alice" || !me.Admin || me.Usage == nil {
t.Errorf("/api/me après installation : %+v", me)
}
// Inscriptions fermées : le second compte est refusé.
w := f.session().json("POST", "/auth/local/register", map[string]string{"username": "bob", "password": "mot-de-passe-bob"})
want(t, w, 403)
}
func TestUploadDownloadRange(t *testing.T) {
f := newFixture(t, nil)
s := f.register("alice")
want(t, s.put("docs/rapport.pdf", "%PDF-0123456789"), 200)
w := s.get("/api/file?path=docs/rapport.pdf")
want(t, w, 200)
if w.Body.String() != "%PDF-0123456789" || !strings.HasPrefix(w.Header().Get("Content-Disposition"), "attachment;") {
t.Errorf("téléchargement : %q %v", w.Body, w.Header())
}
w = s.get("/api/file?path=docs/rapport.pdf", "Range", "bytes=5-9")
want(t, w, 206)
if w.Body.String() != "01234" {
t.Errorf("Range = %q", w.Body)
}
// Remplacement conditionnel par ETag, puis lecture conditionnelle.
etag := s.get("/api/file?path=docs/rapport.pdf").Header().Get("ETag")
want(t, s.get("/api/file?path=docs/rapport.pdf", "If-None-Match", etag), 304)
// Conflit.
want(t, s.put("docs/rapport.pdf", "autre"), 409)
r := s.put("docs/rapport.pdf", "autre", "conflict=rename")
want(t, r, 200)
if e := decode[storage.Entry](t, r); e.Path != "docs/rapport (2).pdf" {
t.Errorf("rename = %q", e.Path)
}
want(t, s.put("docs/rapport.pdf", "v2", "conflict=overwrite"), 200)
want(t, s.put("docs/rapport.pdf", "v3", "conflict=n'importe-quoi"), 400)
vs := decode[[]storage.Version](t, s.get("/api/history?path=docs/rapport.pdf"))
if len(vs) != 1 {
t.Fatalf("versions = %v", vs)
}
old := s.get("/api/history/version?path=docs/rapport.pdf&id=" + vs[0].ID)
if old.Body.String() != "%PDF-0123456789" {
t.Errorf("ancienne version = %q", old.Body)
}
want(t, s.json("POST", "/api/history/restore", map[string]string{"path": "docs/rapport.pdf", "id": vs[0].ID}), 200)
if s.get("/api/file?path=docs/rapport.pdf").Body.String() != "%PDF-0123456789" {
t.Error("restauration")
}
}
func TestActiveContentNeverRunsInOrigin(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("img.svg", `<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>`), 200)
want(t, s.put("note.txt", "bonjour"), 200)
want(t, s.put("photo.png", "\x89PNG"), 200)
want(t, s.put("doc.pdf", "%PDF"), 200)
want(t, s.put("inconnu.xyz", "?"), 200)
for _, name := range []string{"page.html", "img.svg", "inconnu.xyz"} {
for _, inline := range []string{"", "&inline=1"} {
w := s.get("/api/file?path=" + name + inline)
ct := w.Header().Get("Content-Type")
cd := w.Header().Get("Content-Disposition")
if name == "img.svg" && inline != "" {
// SVG affiché en ligne seulement avec un CSP qui interdit tout script.
if !strings.Contains(w.Header().Get("Content-Security-Policy"), "sandbox") {
t.Errorf("SVG inline sans sandbox")
}
continue
}
if strings.Contains(ct, "html") || strings.Contains(ct, "svg") {
t.Errorf("%s%s servi en %s", name, inline, ct)
}
if name == "page.html" && inline != "" {
if !strings.HasPrefix(ct, "text/plain") {
t.Errorf("HTML inline : %s", ct)
}
continue
}
if !strings.HasPrefix(cd, "attachment") {
t.Errorf("%s%s : %s", name, inline, cd)
}
}
}
if w := s.get("/api/file?path=note.txt&inline=1"); !strings.HasPrefix(w.Header().Get("Content-Disposition"), "inline") ||
!strings.HasPrefix(w.Header().Get("Content-Type"), "text/plain") {
t.Errorf("texte inline : %v", w.Header())
}
if w := s.get("/api/file?path=photo.png&inline=1"); w.Header().Get("Content-Type") != "image/png" || w.Header().Get("X-Content-Type-Options") != "nosniff" {
t.Errorf("image inline : %v", w.Header())
}
// PDF en ligne sans CSP sandbox (sinon le lecteur PDF ne s'affiche pas).
if w := s.get("/api/file?path=doc.pdf&inline=1"); w.Header().Get("Content-Type") != "application/pdf" || w.Header().Get("Content-Security-Policy") != "" {
t.Errorf("pdf inline : %v", w.Header())
}
}
func TestContentDispositionEncoding(t *testing.T) {
got := contentDisposition(false, `é"té\.pdf`)
if !strings.Contains(got, `filename="_t_.pdf"`) && !strings.Contains(got, `filename="__t__.pdf"`) {
// repli ASCII : les caractères non ASCII et les guillemets sont remplacés
}
if strings.Contains(got, `"té`) || !strings.Contains(got, "filename*=UTF-8''%C3%A9%22t%C3%A9%5C.pdf") {
t.Errorf("Content-Disposition = %s", got)
}
}
func TestPathTraversalAndInternalFiles(t *testing.T) {
f := newFixture(t, nil)
s := f.register("alice")
for _, p := range []string{".trash/x", "a/.meta.json", ".accounts.json", ".users/alice/home/x"} {
if w := s.put(p, "x"); w.Code != 400 {
t.Errorf("PUT %s : %d", p, w.Code)
}
}
// « .. » ne remonte jamais au-dessus de la racine : le chemin est normalisé sous la racine.
want(t, s.put("../../escape.txt", "x"), 200)
if s.get("/api/file?path=escape.txt").Body.String() != "x" {
t.Error("chemin normalisé sous la racine")
}
if es, _ := os.ReadDir(filepath.Dir(f.root)); len(es) > 0 {
for _, e := range es {
if e.Name() == "escape.txt" {
t.Error("écriture hors racine")
}
}
}
for _, p := range []string{".accounts.json", ".tokens.json", ".session-secret", ".settings.json", ".share-secret", ".meta.json"} {
if w := s.get("/api/file?path=" + p); w.Code == 200 {
t.Errorf("lecture de %s : %s", p, w.Body)
}
}
}
func TestQuotaAndMaxUpload(t *testing.T) {
f := newFixture(t, func(st *storage.Store, sp *storage.Spaces) {
sp.MaxUpload = 1 << 20
st.Defaults.QuotaMB = 1
})
s := f.register("alice")
want(t, s.put(".perso/a.bin", strings.Repeat("x", 700<<10)), 200)
want(t, s.put(".perso/b.bin", strings.Repeat("x", 700<<10)), 507)
want(t, s.put("commun.bin", strings.Repeat("x", 1100<<10)), 413)
me := decode[meResponse](t, s.get("/api/me"))
if me.Usage == nil || me.Usage.Quota != 1<<20 || me.Usage.Used < 700<<10 {
t.Errorf("usage = %+v", me.Usage)
}
}
func TestFolderOperationsAndZip(t *testing.T) {
f := newFixture(t, nil)
s := f.register("alice")
want(t, s.json("POST", "/api/folder", map[string]string{"path": "projet"}), 201)
want(t, s.put("projet/a.txt", "AAA"), 200)
want(t, s.put("projet/sub/b.txt", "BBB"), 200)
want(t, s.put("autre.txt", "CCC"), 200)
want(t, s.json("POST", "/api/copy", map[string]string{"from": "projet", "to": "projet-copie"}), 201)
if s.get("/api/file?path=projet-copie/sub/b.txt").Body.String() != "BBB" {
t.Error("copie de dossier")
}
// ZIP d'un dossier (GET) et d'une sélection (formulaire POST).
w := s.get("/api/zip?path=projet")
want(t, w, 200)
names := zipNames(t, w.Body.Bytes())
if !names["projet/a.txt"] || !names["projet/sub/b.txt"] || !strings.Contains(w.Header().Get("Content-Disposition"), "projet.zip") {
t.Errorf("zip dossier : %v %v", names, w.Header())
}
form := url.Values{"paths": {`["projet/a.txt","autre.txt"]`}}
w = s.do("POST", "/api/zip", strings.NewReader(form.Encode()), "Content-Type", "application/x-www-form-urlencoded")
want(t, w, 200)
if n := zipNames(t, w.Body.Bytes()); !n["a.txt"] || !n["autre.txt"] {
t.Errorf("zip sélection : %v", n)
}
want(t, s.get("/api/zip?path=../../etc"), 404)
// Déplacement multiple avec échec partiel.
want(t, s.put("dest/autre.txt", "déjà là"), 200)
res := decode[[]storage.MoveResult](t, s.json("POST", "/api/move-many", map[string]any{"paths": []string{"autre.txt", "projet/a.txt"}, "dir": "dest"}))
if len(res) != 2 || res[0].Error == "" || res[1].Error != "" {
t.Errorf("move-many = %+v", res)
}
// Corbeille.
want(t, s.do("DELETE", "/api/entry?path=dest&recursive=true", nil), 204)
tr := decode[[]storage.Entry](t, s.get("/api/list?path=.poubelle"))
if len(tr) != 1 || tr[0].Origin != "dest" {
t.Fatalf("poubelle = %+v", tr)
}
want(t, s.json("POST", "/api/trash/restore", map[string]any{"paths": []string{tr[0].Path}}), 200)
if s.get("/api/file?path=dest/a.txt").Body.String() != "AAA" {
t.Error("restauration depuis la poubelle")
}
}
func zipNames(t *testing.T, b []byte) map[string]bool {
t.Helper()
zr, err := zip.NewReader(bytes.NewReader(b), int64(len(b)))
if err != nil {
t.Fatalf("zip illisible : %v", err)
}
out := map[string]bool{}
for _, f := range zr.File {
out[f.Name] = true
}
return out
}
func TestShareFolderWithPassword(t *testing.T) {
f := newFixture(t, nil)
s := f.register("alice")
want(t, s.put("pub/a.txt", "AAA"), 200)
want(t, s.put("pub/sub/b.png", "\x89PNG"), 200)
want(t, s.put("prive.txt", "secret"), 200)
sh := decode[storage.Share](t, s.json("POST", "/api/shares", map[string]any{"path": "pub", "days": 7, "password": "mot-de-passe-partage"}))
if !sh.IsDir || !sh.Protected || sh.Token == "" {
t.Fatalf("share = %+v", sh)
}
visitor := f.session() // sans compte
base := "/api/public/" + sh.Token
// Verrouillé : seuls le titre et l'indication de mot de passe sortent.
info := decode[publicInfo](t, visitor.get(base))
if !info.Protected || info.Name != "" || len(info.Entries) != 0 {
t.Errorf("lien verrouillé : %+v", info)
}
want(t, visitor.get(base+"/file?sub=a.txt"), 401)
want(t, visitor.get(base+"/zip"), 401)
want(t, visitor.json("POST", base+"/unlock", map[string]string{"password": "faux"}), 403)
want(t, visitor.json("POST", base+"/unlock", map[string]string{"password": "mot-de-passe-partage"}), 204)
info = decode[publicInfo](t, visitor.get(base))
if info.Name != "pub" || !info.IsDir || len(info.Entries) != 2 || info.Entries[0].Name != "sub" {
t.Errorf("contenu du lien : %+v", info)
}
if strings.Contains(visitor.get(base).Body.String(), "pub/") || strings.Contains(visitor.get(base).Body.String(), "alice") {
t.Error("le chemin réel ou le propriétaire fuite dans la réponse publique")
}
sub := decode[publicInfo](t, visitor.get(base+"?sub=sub"))
if sub.Name != "sub" || len(sub.Entries) != 1 || sub.Entries[0].Name != "b.png" {
t.Errorf("sous-dossier : %+v", sub)
}
w := visitor.get(base + "/file?sub=a.txt")
want(t, w, 200)
if w.Body.String() != "AAA" {
t.Errorf("fichier partagé = %q", w.Body)
}
want(t, visitor.get(base+"/file?sub=sub/b.png&inline=1"), 200)
// Hors du dossier partagé : refus.
for _, sub := range []string{"../prive.txt", "sub/../../prive.txt", ".trash", "%2e%2e/prive.txt"} {
if w := visitor.get(base + "/file?sub=" + sub); w.Code == 200 {
t.Errorf("sub=%s : %s", sub, w.Body)
}
}
if n := zipNames(t, visitor.get(base+"/zip").Body.Bytes()); !n["pub/a.txt"] || n["prive.txt"] {
t.Errorf("zip public : %v", n)
}
// Le cookie de déverrouillage d'un lien ne vaut pas pour un autre.
sh2 := decode[storage.Share](t, s.json("POST", "/api/shares", map[string]any{"path": "pub", "days": 0, "password": "autre-mot-de-passe"}))
want(t, visitor.get("/api/public/"+sh2.Token+"/file?sub=a.txt"), 401)
// Compteur de téléchargements (hors lecture partielle).
list := decode[[]storage.Share](t, s.get("/api/shares?path=pub"))
var dl int
for _, x := range list {
if x.ID == sh.ID {
dl = x.Downloads
}
}
if dl < 2 {
t.Errorf("téléchargements = %d", dl)
}
// Un jeton falsifié ou révoqué ne donne rien.
want(t, visitor.get("/api/public/"+sh.Token[:len(sh.Token)-3]+"abc"), 404)
want(t, s.do("DELETE", "/api/shares?id="+sh.ID, nil), 204)
want(t, visitor.get(base), 404)
// X-Robots-Tag
if visitor.get("/api/public/xxx").Header().Get("X-Robots-Tag") == "" {
t.Error("X-Robots-Tag absent")
}
}
func TestShareSingleFileAndThumb(t *testing.T) {
f := newFixture(t, nil)
s := f.register("alice")
png := makePNG(t, 900, 300)
want(t, s.put("photo.png", png), 200)
sh := decode[storage.Share](t, s.json("POST", "/api/shares", map[string]any{"path": "photo.png", "days": 1}))
v := f.session()
info := decode[publicInfo](t, v.get("/api/public/"+sh.Token))
if info.IsDir || info.Name != "photo.png" || info.Size != int64(len(png)) || info.Expires == nil {
t.Errorf("info = %+v", info)
}
want(t, v.get("/api/public/"+sh.Token+"?sub=x"), 404) // pas de sous-chemin pour un fichier
w := v.get("/api/public/" + sh.Token + "/thumb")
want(t, w, 200)
if w.Header().Get("Content-Type") != "image/png" {
t.Errorf("thumb : %v", w.Header())
}
// Miniature privée via l'API connectée.
want(t, s.get("/api/thumb?path=photo.png"), 200)
want(t, f.session().get("/api/thumb?path=photo.png"), 401)
}
func TestSettingsAndAdminPermissions(t *testing.T) {
f := newFixture(t, nil)
admin := f.register("alice")
want(t, admin.json("PUT", "/api/settings", map[string]any{"registration": "open"}), 200)
bob := f.register("bob")
me := decode[meResponse](t, bob.get("/api/me"))
if me.Admin || me.User == nil || me.User.Role != "user" {
t.Errorf("bob = %+v", me)
}
// Un utilisateur ordinaire ne règle ni les paramètres, ni le logo, ni les comptes.
want(t, bob.json("PUT", "/api/settings", map[string]any{"title": "X"}), 403)
want(t, bob.do("DELETE", "/api/logo", nil), 403)
want(t, bob.get("/api/admin/users"), 403)
want(t, bob.json("POST", "/api/admin/users", map[string]any{"username": "eve", "password": "mot-de-passe-eve"}), 403)
want(t, bob.json("PATCH", "/api/admin/users/alice", map[string]any{"role": "user"}), 403)
want(t, bob.do("DELETE", "/api/admin/users/alice", nil), 403)
want(t, bob.do("POST", "/api/shares/revoke-all", nil), 403)
// Un visiteur anonyme non plus (route publique /api/logo).
want(t, f.session().do("DELETE", "/api/logo", nil), 403)
want(t, f.session().do("PUT", "/api/logo", strings.NewReader("x")), 403)
st := decode[storage.Settings](t, admin.json("PUT", "/api/settings", map[string]any{"title": "Mon cloud", "quotaMB": 50, "commonReadonly": true, "trashDays": 30}))
if st.Title != "Mon cloud" || st.QuotaMB != 50 || !st.CommonReadonly || st.TrashDays != 30 {
t.Errorf("settings = %+v", st)
}
want(t, admin.json("PUT", "/api/settings", map[string]any{"registration": "nimporte"}), 400)
// Commun en lecture seule : bob ne dépose plus qu'à titre personnel.
want(t, bob.put("x.txt", "x"), 403)
want(t, bob.put(".perso/x.txt", "x"), 200)
want(t, admin.put("admin.txt", "x"), 200)
// Le titre est visible de tous avant connexion.
if m := decode[meResponse](t, f.session().get("/api/me")); m.Title != "Mon cloud" {
t.Errorf("titre public = %q", m.Title)
}
}
func TestAdminUserManagement(t *testing.T) {
f := newFixture(t, nil)
admin := f.register("alice")
want(t, admin.json("PUT", "/api/settings", map[string]any{"registration": "approval"}), 200)
pending := f.register("bob") // 202 : en attente
want(t, pending.get("/api/list?path="), 401)
if m := decode[meResponse](t, admin.get("/api/me")); m.Pending != 1 {
t.Errorf("en attente = %d", m.Pending)
}
users := decode[[]auth.AccountInfo](t, admin.get("/api/admin/users"))
if len(users) != 2 || users[1].Status != "pending" || strings.Contains(admin.get("/api/admin/users").Body.String(), "hash") {
t.Errorf("users = %+v", users)
}
want(t, admin.json("PATCH", "/api/admin/users/bob", map[string]any{"status": "active"}), 200)
bob := f.login("bob")
want(t, bob.put(".perso/mine.txt", "m"), 200)
// Création directe, rôle, mot de passe.
want(t, admin.json("POST", "/api/admin/users", map[string]any{"username": "carl", "name": "Carl", "password": "mot-de-passe-carl", "role": "admin"}), 201)
want(t, admin.json("POST", "/api/admin/users", map[string]any{"username": "carl", "password": "mot-de-passe-carl"}), 400)
want(t, admin.json("PATCH", "/api/admin/users/carl", map[string]any{"password": "nouveau-mot-de-passe"}), 200)
want(t, f.session().json("POST", "/auth/local/login", map[string]string{"username": "carl", "password": "nouveau-mot-de-passe"}), 200)
// Garde-fous.
want(t, admin.do("DELETE", "/api/admin/users/alice", nil), 400) // soi-même
// Désactivation : la session et les jetons de bob cessent de marcher.
tok := decode[struct{ Token string }](t, bob.json("POST", "/api/tokens", map[string]string{"name": "script"}))
api := &session{f: f, cookies: map[string]*http.Cookie{}, bearer: tok.Token}
want(t, api.get("/api/list?path=.perso"), 200)
want(t, admin.json("PATCH", "/api/admin/users/bob", map[string]any{"status": "disabled"}), 200)
want(t, bob.get("/api/list?path="), 401)
want(t, api.get("/api/list?path=.perso"), 401)
// Suppression : l'espace personnel est mis de côté, pas hérité par un homonyme.
want(t, admin.do("DELETE", "/api/admin/users/bob", nil), 204)
again := f.register("bob")
_ = again
want(t, admin.json("PATCH", "/api/admin/users/bob", map[string]any{"status": "active"}), 200)
b2 := f.login("bob")
if es := decode[[]storage.Entry](t, b2.get("/api/list?path=.perso")); len(es) != 0 {
t.Errorf("héritage de l'espace d'un compte supprimé : %+v", es)
}
}
func TestAPITokens(t *testing.T) {
f := newFixture(t, nil)
s := f.register("alice")
created := decode[struct {
ID string
Token string
}](t, s.json("POST", "/api/tokens", map[string]string{"name": "sauvegarde"}))
if !strings.HasPrefix(created.Token, "upd_") {
t.Fatalf("jeton = %q", created.Token)
}
if strings.Contains(s.get("/api/tokens").Body.String(), created.Token) {
t.Error("le secret du jeton est relisible")
}
cli := &session{f: f, cookies: map[string]*http.Cookie{}, bearer: created.Token}
want(t, cli.put("depuis-curl.txt", "ok"), 200)
want(t, cli.get("/api/file?path=depuis-curl.txt"), 200)
// Un jeton ne gère pas les jetons ni les comptes.
want(t, cli.json("POST", "/api/tokens", map[string]string{"name": "x"}), 403)
want(t, cli.get("/api/tokens"), 403)
// Jeton invalide.
bad := &session{f: f, cookies: map[string]*http.Cookie{}, bearer: "upd_faux"}
want(t, bad.get("/api/list?path="), 401)
// Révocation.
want(t, s.do("DELETE", "/api/tokens/"+created.ID, nil), 204)
want(t, cli.get("/api/list?path="), 401)
}
func TestAccountSelfService(t *testing.T) {
f := newFixture(t, nil)
s := f.register("alice")
want(t, s.json("POST", "/api/account/password", map[string]string{"current": "faux", "new": "nouveau-mot-de-passe"}), 403)
want(t, s.json("POST", "/api/account/password", map[string]string{"current": "mot-de-passe-alice", "new": "court"}), 400)
want(t, s.json("POST", "/api/account/password", map[string]string{"current": "mot-de-passe-alice", "new": "nouveau-mot-de-passe"}), 204)
want(t, f.session().json("POST", "/auth/local/login", map[string]string{"username": "alice", "password": "nouveau-mot-de-passe"}), 200)
want(t, s.json("PATCH", "/api/account", map[string]string{"name": "Alice D."}), 204)
if m := decode[meResponse](t, s.get("/api/me")); m.User.Name != "Alice D." {
t.Errorf("nom = %q", m.User.Name)
}
}
func TestTagsFavoritesSearchAndDetails(t *testing.T) {
f := newFixture(t, nil)
s := f.register("alice")
want(t, s.put("notes/plan.md", "# Plan\nle réseau 10.1.2.0/24"), 200)
want(t, s.put("photo.png", makePNG(t, 60, 40)), 200)
want(t, s.json("POST", "/api/meta/tags", map[string]any{"paths": []string{"notes/plan.md"}, "add": []string{"Projet"}}), 204)
want(t, s.json("POST", "/api/meta/favorite", map[string]any{"paths": []string{"photo.png", "notes"}, "favorite": true}), 204)
hits := decode[[]storage.Hit](t, s.get("/api/search?q=10.1.2"))
if len(hits) != 1 || hits[0].Path != "notes/plan.md" || hits[0].Snippet == "" {
t.Errorf("recherche = %+v", hits)
}
if hits = decode[[]storage.Hit](t, s.get("/api/search?tag=projet")); len(hits) != 1 {
t.Errorf("tag = %+v", hits)
}
if favs := decode[[]storage.Entry](t, s.get("/api/list?path=.favoris")); len(favs) != 2 {
t.Errorf("favoris = %+v", favs)
}
es := decode[[]storage.Entry](t, s.get("/api/list?path=&details=1"))
var img, dir *storage.Entry
for i := range es {
switch es[i].Name {
case "photo.png":
img = &es[i]
case "notes":
dir = &es[i]
}
}
if img == nil || img.Details == nil || img.Details.Width != 60 || img.Details.Height != 40 || !img.Favorite {
t.Errorf("image = %+v", img)
}
if dir == nil || dir.Details == nil || dir.Details.Files != 1 || dir.Details.Total == 0 {
t.Errorf("dossier = %+v", dir)
}
h := decode[map[string]string](t, s.get("/api/hash?path=notes/plan.md"))
if len(h["sha256"]) != 64 {
t.Errorf("hash = %v", h)
}
}
+517
View File
@@ -0,0 +1,517 @@
package api
import (
"crypto/sha256"
"encoding/hex"
"io"
"net/http"
"path"
"strconv"
"strings"
"time"
"github.com/vblogio/upandown/internal/storage"
)
func (h *Handler) list(w http.ResponseWriter, r *http.Request) {
u, ok := h.space(w, r)
if !ok {
return
}
entries, err := u.List(r.URL.Query().Get("path"))
if err != nil {
fail(w, err)
return
}
if wantDetails(r) {
ps := make([]*storage.Entry, len(entries))
for i := range entries {
ps[i] = &entries[i]
}
u.AddDetails(ps)
}
w.Header().Set("Cache-Control", "no-store")
writeJSON(w, http.StatusOK, entries)
}
func (h *Handler) search(w http.ResponseWriter, r *http.Request) {
u, ok := h.space(w, r)
if !ok {
return
}
q := r.URL.Query()
f := storage.Filter{Tag: q.Get("tag"), Favorite: q.Get("fav") == "true"}
entries, err := u.Search(q.Get("q"), f, 200)
if err != nil {
fail(w, err)
return
}
if wantDetails(r) {
ps := make([]*storage.Entry, len(entries))
for i := range entries {
ps[i] = &entries[i].Entry
}
u.AddDetails(ps)
}
w.Header().Set("Cache-Control", "no-store")
writeJSON(w, http.StatusOK, entries)
}
func (h *Handler) tags(w http.ResponseWriter, r *http.Request) {
u, ok := h.space(w, r)
if !ok {
return
}
tags, err := u.Tags()
if err != nil {
fail(w, err)
return
}
w.Header().Set("Cache-Control", "no-cache")
writeJSON(w, http.StatusOK, tags)
}
type metaReq struct {
Paths []string `json:"paths"`
Favorite bool `json:"favorite"`
Add []string `json:"add"`
Remove []string `json:"remove"`
Icon string `json:"icon"`
}
func (h *Handler) decodeMeta(w http.ResponseWriter, r *http.Request) (metaReq, bool) {
var req metaReq
if !h.decode(w, r, &req) {
return req, false
}
if len(req.Paths) == 0 || len(req.Paths) > 1000 {
writeErr(w, http.StatusBadRequest, "entre 1 et 1000 chemins attendus")
return req, false
}
return req, true
}
func (h *Handler) setFavorite(w http.ResponseWriter, r *http.Request) {
u, ok := h.space(w, r)
if !ok {
return
}
req, ok := h.decodeMeta(w, r)
if !ok {
return
}
if err := u.SetFavorite(req.Paths, req.Favorite); err != nil {
fail(w, err)
return
}
w.WriteHeader(http.StatusNoContent)
}
func (h *Handler) editTags(w http.ResponseWriter, r *http.Request) {
u, ok := h.space(w, r)
if !ok {
return
}
req, ok := h.decodeMeta(w, r)
if !ok {
return
}
if err := u.EditTags(req.Paths, req.Add, req.Remove); err != nil {
fail(w, err)
return
}
w.WriteHeader(http.StatusNoContent)
}
func (h *Handler) setIcon(w http.ResponseWriter, r *http.Request) {
u, ok := h.space(w, r)
if !ok {
return
}
req, ok := h.decodeMeta(w, r)
if !ok {
return
}
if err := u.SetIcon(req.Paths, req.Icon); err != nil {
fail(w, err)
return
}
w.WriteHeader(http.StatusNoContent)
}
// download sert un fichier (Range, ETag, If-Modified-Since). Sans inline, ou si
// le type n'est pas sûr à afficher, il est téléchargé (Content-Disposition:
// attachment).
func (h *Handler) download(w http.ResponseWriter, r *http.Request) {
u, ok := h.space(w, r)
if !ok {
return
}
f, fi, err := u.Open(r.URL.Query().Get("path"))
if err != nil {
fail(w, err)
return
}
defer f.Close()
serveFile(w, r, f, fi, fi.Name(), r.URL.Query().Get("inline") == "1")
}
// upload dépose un fichier : le corps de la requête est le contenu, lu en flux
// (aucune limite de mémoire). Paramètres : conflict (fail, overwrite, rename),
// mtime (date de modification d'origine, en millisecondes Unix).
func (h *Handler) upload(w http.ResponseWriter, r *http.Request) {
u, ok := h.space(w, r)
if !ok {
return
}
q := r.URL.Query()
o := storage.PutOptions{Conflict: q.Get("conflict"), IfMatch: r.Header.Get("If-Match")}
switch o.Conflict {
case "", "fail", "overwrite", "rename":
default:
writeErr(w, http.StatusBadRequest, "conflict : fail, overwrite ou rename")
return
}
if v := q.Get("mtime"); v != "" {
if ms, err := strconv.ParseInt(v, 10, 64); err == nil {
o.ModTime = time.UnixMilli(ms)
}
}
e, err := u.Put(q.Get("path"), r.Body, r.ContentLength, o)
if err != nil {
// Le corps n'a pas été lu en entier : fermer la connexion plutôt que de la réutiliser.
w.Header().Set("Connection", "close")
fail(w, err)
return
}
writeJSON(w, http.StatusOK, e)
}
type pathReq struct {
Path string `json:"path"`
}
type moveReq struct {
From string `json:"from"`
To string `json:"to"`
}
func (h *Handler) mkdir(w http.ResponseWriter, r *http.Request) {
u, ok := h.space(w, r)
if !ok {
return
}
var req pathReq
if !h.decode(w, r, &req) {
return
}
entry, err := u.Mkdir(req.Path)
if err != nil {
fail(w, err)
return
}
writeJSON(w, http.StatusCreated, entry)
}
func (h *Handler) move(w http.ResponseWriter, r *http.Request) {
u, ok := h.space(w, r)
if !ok {
return
}
var req moveReq
if !h.decode(w, r, &req) {
return
}
entry, err := u.Move(req.From, req.To)
if err != nil {
fail(w, err)
return
}
writeJSON(w, http.StatusOK, entry)
}
type moveManyReq struct {
Paths []string `json:"paths"`
Dir string `json:"dir"`
}
// moveMany renvoie toujours 200 avec le détail par élément : le client
// affiche les échecs partiels (ex. nom déjà pris dans la destination).
func (h *Handler) moveMany(w http.ResponseWriter, r *http.Request) {
u, ok := h.space(w, r)
if !ok {
return
}
var req moveManyReq
if !h.decode(w, r, &req) {
return
}
if len(req.Paths) == 0 || len(req.Paths) > 1000 {
writeErr(w, http.StatusBadRequest, "entre 1 et 1000 chemins attendus")
return
}
res, err := u.MoveMany(req.Paths, req.Dir)
if err != nil {
fail(w, err)
return
}
writeJSON(w, http.StatusOK, res)
}
func (h *Handler) copy(w http.ResponseWriter, r *http.Request) {
u, ok := h.space(w, r)
if !ok {
return
}
var req moveReq
if !h.decode(w, r, &req) {
return
}
entry, err := u.Copy(req.From, req.To)
if err != nil {
fail(w, err)
return
}
writeJSON(w, http.StatusCreated, entry)
}
func (h *Handler) delete(w http.ResponseWriter, r *http.Request) {
u, ok := h.space(w, r)
if !ok {
return
}
q := r.URL.Query()
if err := u.Delete(q.Get("path"), q.Get("recursive") == "true"); err != nil {
fail(w, err)
return
}
w.WriteHeader(http.StatusNoContent)
}
func (h *Handler) restoreTrash(w http.ResponseWriter, r *http.Request) {
u, ok := h.space(w, r)
if !ok {
return
}
req, ok := h.decodeMeta(w, r)
if !ok {
return
}
writeJSON(w, http.StatusOK, u.RestoreTrash(req.Paths))
}
func (h *Handler) thumb(w http.ResponseWriter, r *http.Request) {
u, ok := h.space(w, r)
if !ok {
return
}
data, typ, mod, err := u.Thumb(r.URL.Query().Get("path"))
if err != nil {
w.Header().Set("Cache-Control", "no-store")
fail(w, err)
return
}
writeThumb(w, data, typ, mod)
}
func writeThumb(w http.ResponseWriter, data []byte, typ string, mod time.Time) {
// L'URL porte la date du fichier (?v=...) : une nouvelle version change l'URL.
w.Header().Set("Cache-Control", "private, max-age=86400")
w.Header().Set("Content-Type", typ)
w.Header().Set("Last-Modified", mod.UTC().Format(http.TimeFormat))
_, _ = w.Write(data)
}
// zip envoie un dossier ou une sélection en archive ZIP. GET ?path=x pour un
// élément ; POST (formulaire) avec paths = tableau JSON de chemins.
func (h *Handler) zip(w http.ResponseWriter, r *http.Request) {
u, ok := h.space(w, r)
if !ok {
return
}
var paths []string
if r.Method == http.MethodPost {
r.Body = http.MaxBytesReader(w, r.Body, 4<<20)
if err := r.ParseForm(); err != nil {
writeErr(w, http.StatusBadRequest, "formulaire invalide")
return
}
if err := jsonUnmarshal(r.PostForm.Get("paths"), &paths); err != nil {
writeErr(w, http.StatusBadRequest, "paths : tableau JSON attendu")
return
}
} else {
paths = r.URL.Query()["path"]
}
if len(paths) == 0 || len(paths) > 5000 {
writeErr(w, http.StatusBadRequest, "entre 1 et 5000 chemins attendus")
return
}
items, name, err := u.ZipItems(paths)
if err != nil {
fail(w, err)
return
}
w.Header().Set("Content-Type", "application/zip")
w.Header().Set("Content-Disposition", contentDisposition(false, name+".zip"))
w.Header().Set("Cache-Control", "no-store")
if err := storage.WriteZip(w, items); err != nil {
panic(http.ErrAbortHandler) // archive tronquée : couper la connexion plutôt qu'annoncer une fin normale
}
}
// hash calcule l'empreinte SHA-256 d'un fichier.
func (h *Handler) hash(w http.ResponseWriter, r *http.Request) {
u, ok := h.space(w, r)
if !ok {
return
}
f, _, err := u.Open(r.URL.Query().Get("path"))
if err != nil {
fail(w, err)
return
}
defer f.Close()
sum := sha256.New()
if _, err := io.Copy(sum, f); err != nil {
fail(w, err)
return
}
writeJSON(w, http.StatusOK, map[string]string{"sha256": hex.EncodeToString(sum.Sum(nil))})
}
func (h *Handler) history(w http.ResponseWriter, r *http.Request) {
u, ok := h.space(w, r)
if !ok {
return
}
vs, err := u.Versions(r.URL.Query().Get("path"))
if err != nil {
fail(w, err)
return
}
w.Header().Set("Cache-Control", "no-cache")
writeJSON(w, http.StatusOK, vs)
}
// readVersion télécharge une version ancienne d'un fichier.
func (h *Handler) readVersion(w http.ResponseWriter, r *http.Request) {
u, ok := h.space(w, r)
if !ok {
return
}
q := r.URL.Query()
f, fi, err := u.OpenVersion(q.Get("path"), q.Get("id"))
if err != nil {
fail(w, err)
return
}
defer f.Close()
serveFile(w, r, f, fi, path.Base(q.Get("path")), false)
}
func (h *Handler) snapshot(w http.ResponseWriter, r *http.Request) {
u, ok := h.space(w, r)
if !ok {
return
}
var req pathReq
if !h.decode(w, r, &req) {
return
}
v, err := u.Snapshot(req.Path)
if err != nil {
fail(w, err)
return
}
writeJSON(w, http.StatusOK, v)
}
type restoreReq struct {
Path string `json:"path"`
ID string `json:"id"`
}
func (h *Handler) restore(w http.ResponseWriter, r *http.Request) {
u, ok := h.space(w, r)
if !ok {
return
}
var req restoreReq
if !h.decode(w, r, &req) {
return
}
entry, err := u.Restore(req.Path, req.ID)
if err != nil {
fail(w, err)
return
}
writeJSON(w, http.StatusOK, entry)
}
func (h *Handler) shares(w http.ResponseWriter, r *http.Request) {
u, ok := h.space(w, r)
if !ok {
return
}
l, err := u.Shares(r.URL.Query().Get("path"))
if err != nil {
fail(w, err)
return
}
w.Header().Set("Cache-Control", "no-store")
writeJSON(w, http.StatusOK, l)
}
type shareReq struct {
Path string `json:"path"`
Days int `json:"days"`
Password string `json:"password"`
}
func (h *Handler) createShare(w http.ResponseWriter, r *http.Request) {
u, ok := h.space(w, r)
if !ok {
return
}
var req shareReq
if !h.decode(w, r, &req) {
return
}
if req.Days < 0 || req.Days > 3650 {
writeErr(w, http.StatusBadRequest, "durée de 0 (sans expiration) à 3650 jours")
return
}
sh, err := u.CreateShare(req.Path, storage.ShareOptions{TTL: time.Duration(req.Days) * 24 * time.Hour, Password: req.Password})
if err != nil {
fail(w, err)
return
}
writeJSON(w, http.StatusCreated, sh)
}
func (h *Handler) revokeShare(w http.ResponseWriter, r *http.Request) {
u, ok := h.space(w, r)
if !ok {
return
}
if err := u.RevokeShare(r.URL.Query().Get("id")); err != nil {
fail(w, err)
return
}
w.WriteHeader(http.StatusNoContent)
}
func (h *Handler) revokeAllShares(w http.ResponseWriter, r *http.Request) {
u, ok := h.space(w, r)
if !ok {
return
}
if err := u.RevokeAllShares(); err != nil {
fail(w, err)
return
}
w.WriteHeader(http.StatusNoContent)
}
func jsonUnmarshal(s string, v any) error { return jsonDecode(strings.NewReader(s), v) }
+233
View File
@@ -0,0 +1,233 @@
package api
import (
"errors"
"io"
"log/slog"
"net/http"
"github.com/vblogio/upandown/internal/auth"
"github.com/vblogio/upandown/internal/storage"
)
type meUser struct {
ID string `json:"id"`
Name string `json:"name"`
Email string `json:"email,omitempty"`
Role string `json:"role"`
Provider string `json:"provider,omitempty"`
}
type usage struct {
Used int64 `json:"used"`
Quota int64 `json:"quota"` // 0 : illimité
}
// meResponse est lu avant la connexion (page de connexion : fournisseurs,
// inscription, titre) puis après (utilisateur, droits, occupation).
type meResponse struct {
Mode string `json:"mode"` // none, local, oidc ou both
Local bool `json:"local"`
OIDC bool `json:"oidc"`
OIDCName string `json:"oidcName,omitempty"`
Registration string `json:"registration"` // closed, approval ou open (comptes locaux)
Setup bool `json:"setup,omitempty"`
Title string `json:"title"`
Logo string `json:"logo,omitempty"`
Version string `json:"version,omitempty"`
User *meUser `json:"user,omitempty"`
Admin bool `json:"admin"`
CanChangePW bool `json:"canChangePassword,omitempty"`
Logout string `json:"logout,omitempty"`
Usage *usage `json:"usage,omitempty"`
CommonReadonly bool `json:"commonReadonly"`
Pending int `json:"pending,omitempty"` // administrateur : inscriptions à valider
}
func (h *Handler) me(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "no-store")
st, err := h.Store.ReadSettings()
if err != nil {
fail(w, err)
return
}
m := meResponse{Mode: h.Mode, Local: h.Mode == "local" || h.Mode == "both", OIDC: h.Mode == "oidc" || h.Mode == "both",
OIDCName: h.OIDCName, Registration: st.Registration, Title: st.Title, Logo: st.Logo, Version: h.Version,
CommonReadonly: st.CommonReadonly}
if !m.Local {
m.Registration = storage.RegClosed
}
if h.Accounts != nil {
m.Setup = m.Local && h.Accounts.NeedsSetup()
}
u := auth.UserFrom(r.Context())
switch {
case u != nil:
m.User = &meUser{ID: u.ID, Name: u.Name, Email: u.Email, Role: u.Role, Provider: u.Provider}
m.Logout = "/auth/logout"
m.CanChangePW = u.Provider == auth.ProviderLocal
case h.Mode == "none":
m.User = &meUser{ID: storage.LocalUser, Name: "Utilisateur", Role: auth.RoleAdmin}
}
if m.User != nil {
m.Admin = h.isAdmin(r)
if sp, err := h.Spaces.For(userID(r), m.Admin); err == nil {
used, quota := sp.Usage()
m.Usage = &usage{Used: used, Quota: quota}
}
if m.Admin && h.Accounts != nil {
m.Pending = h.Accounts.PendingCount()
}
}
writeJSON(w, http.StatusOK, m)
}
// --- Paramètres et logo ---------------------------------------------------------------
func (h *Handler) readSettings(w http.ResponseWriter, r *http.Request) {
st, err := h.Store.ReadSettings()
if err != nil {
fail(w, err)
return
}
w.Header().Set("Cache-Control", "no-cache")
writeJSON(w, http.StatusOK, st)
}
// settingsReq : seuls les champs présents sont modifiés.
type settingsReq struct {
Title *string `json:"title"`
TrashDays *int `json:"trashDays"`
Registration *string `json:"registration"`
QuotaMB *int64 `json:"quotaMB"`
CommonReadonly *bool `json:"commonReadonly"`
}
func (h *Handler) writeSettings(w http.ResponseWriter, r *http.Request) {
if !h.admin(w, r) {
return
}
var req settingsReq
if !h.decode(w, r, &req) {
return
}
st, err := h.Store.ReadSettings()
if err == nil && req.Title != nil {
st, err = h.Store.WriteTitle(*req.Title)
}
if err == nil && req.Registration != nil {
st, err = h.Store.WriteRegistration(*req.Registration)
}
if err == nil && req.QuotaMB != nil {
st, err = h.Store.WriteQuota(*req.QuotaMB)
}
if err == nil && req.CommonReadonly != nil {
st, err = h.Store.WriteCommonReadonly(*req.CommonReadonly)
}
if err == nil && req.TrashDays != nil {
if st, err = h.Store.WriteTrashDays(*req.TrashDays); err == nil {
if perr := h.Spaces.PurgeTrash(); perr != nil {
slog.Warn("poubelle : purge incomplète", "err", perr)
}
}
}
if err != nil {
fail(w, err)
return
}
writeJSON(w, http.StatusOK, st)
}
func (h *Handler) readLogo(w http.ResponseWriter, r *http.Request) {
data, err := h.Store.ReadLogo()
if err != nil {
w.Header().Set("Cache-Control", "no-store")
fail(w, err)
return
}
// L'URL porte la version du logo (?v=...) : un nouveau logo change l'URL.
w.Header().Set("Cache-Control", "private, max-age=86400")
w.Header().Set("Content-Type", "image/png")
_, _ = w.Write(data)
}
func (h *Handler) writeLogo(w http.ResponseWriter, r *http.Request) {
if !h.admin(w, r) {
return
}
data, err := io.ReadAll(http.MaxBytesReader(w, r.Body, storage.MaxLogoUpload))
if err != nil {
fail(w, err)
return
}
st, err := h.Store.WriteLogo(data)
if err != nil {
fail(w, err)
return
}
writeJSON(w, http.StatusOK, st)
}
func (h *Handler) deleteLogo(w http.ResponseWriter, r *http.Request) {
if !h.admin(w, r) {
return
}
st, err := h.Store.DeleteLogo()
if err != nil {
fail(w, err)
return
}
writeJSON(w, http.StatusOK, st)
}
// --- Compte ------------------------------------------------------------------------------
func accountErr(w http.ResponseWriter, err error) {
switch {
case errors.Is(err, auth.ErrNoAccount):
writeErr(w, http.StatusNotFound, err.Error())
case errors.Is(err, auth.ErrBadCredentials):
writeErr(w, http.StatusForbidden, "mot de passe actuel incorrect")
case errors.Is(err, auth.ErrInvalidAccount), errors.Is(err, auth.ErrLastAdmin), errors.Is(err, auth.ErrAccountExists):
writeErr(w, http.StatusBadRequest, err.Error())
default:
slog.Error("compte", "err", err)
writeErr(w, http.StatusInternalServerError, "erreur interne")
}
}
func (h *Handler) changePassword(w http.ResponseWriter, r *http.Request) {
var req struct {
Current string `json:"current"`
New string `json:"new"`
}
if !h.decode(w, r, &req) {
return
}
if err := h.Accounts.ChangePassword(userID(r), req.Current, req.New); err != nil {
accountErr(w, err)
return
}
w.WriteHeader(http.StatusNoContent)
}
func (h *Handler) patchAccount(w http.ResponseWriter, r *http.Request) {
var req struct {
Name *string `json:"name"`
Email *string `json:"email"`
}
if !h.decode(w, r, &req) {
return
}
acc, ok := h.Accounts.Get(userID(r))
if !ok || acc.Provider != auth.ProviderLocal {
writeErr(w, http.StatusBadRequest, "profil géré par le fournisseur d'identité")
return
}
if _, err := h.Accounts.Update(acc.ID, auth.Patch{Name: req.Name, Email: req.Email}); err != nil {
accountErr(w, err)
return
}
w.WriteHeader(http.StatusNoContent)
}
+223
View File
@@ -0,0 +1,223 @@
package api
import (
"errors"
"net/http"
"time"
"github.com/vblogio/upandown/internal/storage"
)
// Liens de partage publics : /s/<jeton> dans l'interface, /api/public/<jeton>
// pour les données. Rien d'autre n'est accessible sans authentification : ni
// l'explorateur, ni les chemins réels (les entrées sont décrites relativement
// à l'élément partagé).
const unlockCookiePrefix = "ud_share_"
type publicEntry struct {
Name string `json:"name"`
IsDir bool `json:"isDir"`
Size int64 `json:"size"`
ModTime time.Time `json:"modTime"`
}
type publicInfo struct {
Title string `json:"title"`
Logo string `json:"logo,omitempty"`
Protected bool `json:"protected,omitempty"` // mot de passe requis (rien d'autre n'est révélé)
Name string `json:"name,omitempty"`
IsDir bool `json:"isDir"`
Size int64 `json:"size"`
ModTime time.Time `json:"modTime"`
Sub string `json:"sub,omitempty"` // dossier affiché, relatif à l'élément partagé
Entries []publicEntry `json:"entries,omitempty"`
Expires *time.Time `json:"expires,omitempty"`
}
// shared résout le lien de la requête et vérifie le déverrouillage s'il est
// protégé par un mot de passe.
func (h *Handler) shared(w http.ResponseWriter, r *http.Request) (storage.Share, *storage.Store, bool, bool) {
w.Header().Set("Cache-Control", "no-store")
w.Header().Set("X-Robots-Tag", "noindex, nofollow")
sh, st, err := h.Spaces.ResolveShare(r.PathValue("token"))
if err != nil {
if errors.Is(err, storage.ErrNotFound) {
writeErr(w, http.StatusNotFound, "lien invalide, expiré ou révoqué")
} else {
fail(w, err)
}
return sh, nil, false, false
}
unlocked := true
if sh.Protected {
want, err := st.UnlockCookie(sh)
c, cerr := r.Cookie(unlockCookiePrefix + sh.ID)
unlocked = err == nil && cerr == nil && c.Value == want
}
return sh, st, unlocked, true
}
// sharedItem renvoie le Store et le chemin de l'élément visé (sub : sous-chemin
// demandé), en refusant l'accès tant que le lien n'est pas déverrouillé.
func (h *Handler) sharedItem(w http.ResponseWriter, r *http.Request) (storage.Share, *storage.Store, string, string, bool) {
sh, st, unlocked, ok := h.shared(w, r)
if !ok {
return sh, nil, "", "", false
}
if !unlocked {
writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "mot de passe requis", "code": "password"})
return sh, nil, "", "", false
}
sub := r.URL.Query().Get("sub")
full, err := storage.SharedPath(sh, sub)
if err != nil {
fail(w, err)
return sh, nil, "", "", false
}
return sh, st, full, sub, true
}
func (h *Handler) branding(info *publicInfo) {
if st, err := h.Store.ReadSettings(); err == nil {
info.Title, info.Logo = st.Title, st.Logo
}
}
func (h *Handler) publicInfo(w http.ResponseWriter, r *http.Request) {
sh, st, unlocked, ok := h.shared(w, r)
if !ok {
return
}
var info publicInfo
h.branding(&info)
if !unlocked {
info.Protected = true
writeJSON(w, http.StatusOK, info)
return
}
sub := r.URL.Query().Get("sub")
full, err := storage.SharedPath(sh, sub)
if err != nil {
fail(w, err)
return
}
e, err := st.Stat(full)
if err != nil {
fail(w, err)
return
}
info.Name, info.IsDir, info.Size, info.ModTime, info.Sub, info.Expires = e.Name, e.IsDir, e.Size, e.ModTime, sub, sh.Expires
if sub == "" {
info.Name = baseName(sh.Path)
}
if e.IsDir {
es, err := st.List(full)
if err != nil {
fail(w, err)
return
}
info.Entries = make([]publicEntry, 0, len(es))
for _, x := range es {
info.Entries = append(info.Entries, publicEntry{Name: x.Name, IsDir: x.IsDir, Size: x.Size, ModTime: x.ModTime})
}
}
writeJSON(w, http.StatusOK, info)
}
func baseName(p string) string {
for i := len(p) - 1; i >= 0; i-- {
if p[i] == '/' {
return p[i+1:]
}
}
return p
}
// publicUnlock vérifie le mot de passe d'un lien protégé et pose le cookie de
// déverrouillage (12 h).
func (h *Handler) publicUnlock(w http.ResponseWriter, r *http.Request) {
sh, st, _, ok := h.shared(w, r)
if !ok {
return
}
var req struct {
Password string `json:"password"`
}
if !h.decode(w, r, &req) {
return
}
key := sh.ID + "|" + r.RemoteAddr
if !h.unlocks.Allowed(key) {
w.Header().Set("Retry-After", "900")
writeErr(w, http.StatusTooManyRequests, "trop de tentatives : réessayer dans quelques minutes")
return
}
if !sh.CheckPassword(req.Password) {
h.unlocks.Fail(key)
writeErr(w, http.StatusForbidden, "mot de passe incorrect")
return
}
h.unlocks.Reset(key)
v, err := st.UnlockCookie(sh)
if err != nil {
fail(w, err)
return
}
http.SetCookie(w, &http.Cookie{
Name: unlockCookiePrefix + sh.ID, Value: v, Path: "/",
MaxAge: int((12 * time.Hour).Seconds()), HttpOnly: true, SameSite: http.SameSiteLaxMode,
Secure: secure(r) || h.SecureCookies,
})
w.WriteHeader(http.StatusNoContent)
}
func (h *Handler) publicFile(w http.ResponseWriter, r *http.Request) {
sh, 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()
inline := r.URL.Query().Get("inline") == "1"
if !inline && r.Header.Get("Range") == "" {
st.CountDownload(sh.ID)
}
serveFile(w, r, f, fi, fi.Name(), inline)
}
func (h *Handler) publicZip(w http.ResponseWriter, r *http.Request) {
sh, st, full, _, ok := h.sharedItem(w, r)
if !ok {
return
}
item, err := st.SharedZipItem(full)
if err != nil {
fail(w, err)
return
}
st.CountDownload(sh.ID)
w.Header().Set("Content-Type", "application/zip")
w.Header().Set("Content-Disposition", contentDisposition(false, item.Name+".zip"))
if err := storage.WriteZip(w, []storage.ZipItem{item}); err != nil {
panic(http.ErrAbortHandler)
}
}
func (h *Handler) publicThumb(w http.ResponseWriter, r *http.Request) {
_, st, full, _, ok := h.sharedItem(w, r)
if !ok {
return
}
data, typ, mod, err := st.Thumb(full)
if err != nil {
fail(w, err)
return
}
// Réponse protégée : pas de cache partagé.
writeThumb(w, data, typ, mod)
}
+94
View File
@@ -0,0 +1,94 @@
package api
import (
"encoding/json"
"io"
"io/fs"
"mime"
"net/http"
"net/url"
"os"
"path"
"strings"
"github.com/vblogio/upandown/internal/storage"
)
func jsonDecode(r io.Reader, v any) error { return json.NewDecoder(r).Decode(v) }
// inlineTypes : types MIME affichables dans le navigateur sans risque. Tout le
// reste est servi en téléchargement (Content-Disposition: attachment), pour
// qu'un fichier HTML ou un script déposé ne s'exécute jamais dans l'origine de
// l'application.
var inlineTypes = map[string]bool{
"image/png": true, "image/jpeg": true, "image/gif": true, "image/webp": true, "image/avif": true,
"image/bmp": true, "image/x-icon": true, "image/vnd.microsoft.icon": true, "image/svg+xml": true,
"video/mp4": true, "video/webm": true, "video/ogg": true, "video/quicktime": true, "video/x-m4v": true,
"audio/mpeg": true, "audio/ogg": true, "audio/wav": true, "audio/x-wav": true, "audio/flac": true,
"audio/aac": true, "audio/mp4": true, "audio/x-m4a": true, "audio/webm": true, "audio/opus": true,
"application/pdf": true,
}
// contentType renvoie le type MIME d'un fichier d'après son extension. Les
// fichiers texte sont toujours servis en text/plain (jamais en HTML ou XML).
func contentType(name string) string {
if storage.IsText(name) {
return "text/plain; charset=utf-8"
}
t := mime.TypeByExtension(strings.ToLower(path.Ext(name)))
if t == "" {
return "application/octet-stream"
}
return t
}
func baseType(t string) string {
t, _, _ = strings.Cut(t, ";")
return strings.TrimSpace(strings.ToLower(t))
}
// contentDisposition construit l'en-tête avec un nom ASCII de repli et le nom
// UTF-8 d'origine (RFC 6266 / 5987).
func contentDisposition(inline bool, name string) string {
kind := "attachment"
if inline {
kind = "inline"
}
ascii := strings.Map(func(r rune) rune {
if r < 0x20 || r > 0x7e || r == '"' || r == '\\' || r == '%' {
return '_'
}
return r
}, name)
return kind + `; filename="` + ascii + `"; filename*=UTF-8''` + url.PathEscape(name)
}
// serveFile envoie un fichier avec prise en charge de Range, If-Modified-Since
// et ETag. Affichage en ligne seulement si inline est demandé et que le type
// est sûr ; sinon téléchargement.
func serveFile(w http.ResponseWriter, r *http.Request, f *os.File, fi fs.FileInfo, name string, inline bool) {
ct := contentType(name)
bt := baseType(ct)
showInline := inline && (inlineTypes[bt] || strings.HasPrefix(ct, "text/plain"))
if !showInline {
ct = "application/octet-stream"
if t := mime.TypeByExtension(strings.ToLower(path.Ext(name))); t != "" && !showInline {
ct = t
}
// Un téléchargement n'est jamais interprété : type générique pour les types actifs.
if bt := baseType(ct); bt == "text/html" || bt == "application/xhtml+xml" || bt == "image/svg+xml" || bt == "text/xml" || bt == "application/xml" {
ct = "application/octet-stream"
}
}
h := w.Header()
h.Set("Content-Type", ct)
h.Set("Content-Disposition", contentDisposition(showInline, name))
h.Set("ETag", storage.ETag(fi))
h.Set("Cache-Control", "private, no-cache")
h.Set("X-Content-Type-Options", "nosniff")
if showInline && bt != "application/pdf" {
// Aucun script ni sous-ressource, même en navigation directe (SVG).
h.Set("Content-Security-Policy", "sandbox; default-src 'none'; img-src data:; media-src 'self'; style-src 'unsafe-inline'")
}
http.ServeContent(w, r, name, fi.ModTime(), f)
}