Up And Down : première version
This commit is contained in:
commit
89c5430308
76 files changed
+20730
No files matched your search
@@ -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)
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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) }
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -0,0 +1,677 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"crypto/pbkdf2"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"crypto/subtle"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// Comptes utilisateurs : comptes locaux (identifiant + mot de passe) et comptes
|
||||
// créés à la première connexion OIDC, conservés dans DATA_DIR/.accounts.json
|
||||
// (0600). Les mots de passe ne sont gardés que sous forme d'empreinte
|
||||
// PBKDF2-SHA256 salée.
|
||||
|
||||
const accountsFile = ".accounts.json"
|
||||
|
||||
// Rôles et états d'un compte.
|
||||
const (
|
||||
RoleAdmin = "admin"
|
||||
RoleUser = "user"
|
||||
|
||||
StatusActive = "active"
|
||||
StatusPending = "pending" // inscription à valider par un administrateur
|
||||
StatusDisabled = "disabled" // connexion refusée
|
||||
)
|
||||
|
||||
// Fournisseurs d'identité.
|
||||
const (
|
||||
ProviderLocal = "local"
|
||||
ProviderOIDC = "oidc"
|
||||
)
|
||||
|
||||
const (
|
||||
minPasswordLen = 10
|
||||
maxPasswordLen = 200
|
||||
maxNameLen = 80
|
||||
)
|
||||
|
||||
// pbkdf2Iter : itérations PBKDF2-SHA256 (variable pour accélérer les tests).
|
||||
var pbkdf2Iter = 600_000
|
||||
|
||||
var (
|
||||
ErrInvalidAccount = errors.New("compte invalide")
|
||||
ErrAccountExists = errors.New("identifiant déjà utilisé")
|
||||
ErrNoAccount = errors.New("compte introuvable")
|
||||
ErrLastAdmin = errors.New("il doit rester au moins un administrateur actif")
|
||||
)
|
||||
|
||||
var usernameRe = regexp.MustCompile(`^[a-z0-9][a-z0-9._-]{2,31}$`)
|
||||
|
||||
// Account est un compte enregistré.
|
||||
type Account struct {
|
||||
ID string `json:"id"` // nom de l'espace personnel (storage.UserID)
|
||||
Username string `json:"username,omitempty"` // compte local : identifiant de connexion
|
||||
Name string `json:"name"`
|
||||
Email string `json:"email,omitempty"`
|
||||
Provider string `json:"provider"`
|
||||
Sub string `json:"sub,omitempty"` // compte OIDC : sujet du jeton
|
||||
Role string `json:"role"`
|
||||
Status string `json:"status"`
|
||||
Hash string `json:"hash,omitempty"`
|
||||
Created time.Time `json:"created"`
|
||||
LastLogin time.Time `json:"lastLogin,omitzero"`
|
||||
}
|
||||
|
||||
// AccountInfo est la vue d'un compte renvoyée à l'interface d'administration.
|
||||
type AccountInfo struct {
|
||||
ID string `json:"id"`
|
||||
Username string `json:"username,omitempty"`
|
||||
Name string `json:"name"`
|
||||
Email string `json:"email,omitempty"`
|
||||
Provider string `json:"provider"`
|
||||
Role string `json:"role"`
|
||||
Status string `json:"status"`
|
||||
Created time.Time `json:"created"`
|
||||
LastLogin time.Time `json:"lastLogin,omitzero"`
|
||||
}
|
||||
|
||||
// Info renvoie la vue publique du compte (sans empreinte).
|
||||
func (a Account) Info() AccountInfo {
|
||||
return AccountInfo{ID: a.ID, Username: a.Username, Name: a.Name, Email: a.Email, Provider: a.Provider,
|
||||
Role: a.Role, Status: a.Status, Created: a.Created, LastLogin: a.LastLogin}
|
||||
}
|
||||
|
||||
// User renvoie l'utilisateur de session correspondant au compte.
|
||||
func (a Account) User() User {
|
||||
return User{ID: a.ID, Sub: a.Sub, Name: a.Name, Email: a.Email, Provider: a.Provider, Role: a.Role}
|
||||
}
|
||||
|
||||
// Accounts conserve les comptes dans dir/.accounts.json.
|
||||
type Accounts struct {
|
||||
mu sync.Mutex
|
||||
file string
|
||||
byID map[string]*Account
|
||||
dummy string // empreinte factice : égalise le temps de réponse d'un identifiant inconnu
|
||||
}
|
||||
|
||||
// OpenAccounts charge (ou crée) le fichier des comptes de dir.
|
||||
func OpenAccounts(dir string) (*Accounts, error) {
|
||||
a := &Accounts{file: filepath.Join(dir, accountsFile), byID: map[string]*Account{}}
|
||||
b, err := os.ReadFile(a.file)
|
||||
switch {
|
||||
case errors.Is(err, os.ErrNotExist):
|
||||
case err != nil:
|
||||
return nil, err
|
||||
default:
|
||||
var d struct {
|
||||
Accounts []*Account `json:"accounts"`
|
||||
}
|
||||
if err := json.Unmarshal(b, &d); err != nil {
|
||||
return nil, errors.New(a.file + " invalide : " + err.Error())
|
||||
}
|
||||
for _, acc := range d.Accounts {
|
||||
a.byID[acc.ID] = acc
|
||||
}
|
||||
}
|
||||
a.dummy = hashPassword("mot de passe factice")
|
||||
return a, nil
|
||||
}
|
||||
|
||||
// save écrit le fichier ; appelé sous mu.
|
||||
func (a *Accounts) save() error {
|
||||
list := make([]*Account, 0, len(a.byID))
|
||||
for _, acc := range a.byID {
|
||||
list = append(list, acc)
|
||||
}
|
||||
sort.Slice(list, func(i, j int) bool { return list[i].Created.Before(list[j].Created) })
|
||||
b, err := json.MarshalIndent(map[string]any{"accounts": list}, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tmp, err := os.CreateTemp(filepath.Dir(a.file), ".tmp-*")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer os.Remove(tmp.Name())
|
||||
if err := tmp.Chmod(0o600); err != nil {
|
||||
tmp.Close()
|
||||
return err
|
||||
}
|
||||
if _, err := tmp.Write(b); err != nil {
|
||||
tmp.Close()
|
||||
return err
|
||||
}
|
||||
if err := tmp.Sync(); err != nil {
|
||||
tmp.Close()
|
||||
return err
|
||||
}
|
||||
if err := tmp.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Rename(tmp.Name(), a.file)
|
||||
}
|
||||
|
||||
// --- Mots de passe ------------------------------------------------------------------
|
||||
|
||||
func hashPassword(pw string) string {
|
||||
salt := make([]byte, 16)
|
||||
_, _ = rand.Read(salt)
|
||||
return deriveHash(pw, salt, pbkdf2Iter)
|
||||
}
|
||||
|
||||
func deriveHash(pw string, salt []byte, iter int) string {
|
||||
h, err := pbkdf2.Key(sha256.New, pw, salt, iter, 32)
|
||||
if err != nil {
|
||||
panic(err) // paramètres constants valides
|
||||
}
|
||||
return fmt.Sprintf("pbkdf2-sha256$%d$%s$%s", iter, b64.EncodeToString(salt), b64.EncodeToString(h))
|
||||
}
|
||||
|
||||
func checkPassword(hash, pw string) bool {
|
||||
parts := strings.Split(hash, "$")
|
||||
if len(parts) != 4 || parts[0] != "pbkdf2-sha256" {
|
||||
return false
|
||||
}
|
||||
iter, err := strconv.Atoi(parts[1])
|
||||
if err != nil || iter < 1 || iter > 10_000_000 {
|
||||
return false
|
||||
}
|
||||
salt, err := b64.DecodeString(parts[2])
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return subtle.ConstantTimeCompare([]byte(deriveHash(pw, salt, iter)), []byte(hash)) == 1
|
||||
}
|
||||
|
||||
// ValidatePassword vérifie la longueur d'un nouveau mot de passe.
|
||||
func ValidatePassword(pw string) error {
|
||||
if n := utf8.RuneCountInString(pw); n < minPasswordLen || len(pw) > maxPasswordLen {
|
||||
return fmt.Errorf("%w : mot de passe de %d à %d caractères", ErrInvalidAccount, minPasswordLen, maxPasswordLen)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// --- Lecture ---------------------------------------------------------------------------
|
||||
|
||||
// Get renvoie le compte d'identifiant id.
|
||||
func (a *Accounts) Get(id string) (Account, bool) {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if acc, ok := a.byID[id]; ok {
|
||||
return *acc, true
|
||||
}
|
||||
return Account{}, false
|
||||
}
|
||||
|
||||
// List renvoie tous les comptes, du plus ancien au plus récent.
|
||||
func (a *Accounts) List() []AccountInfo {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
out := make([]AccountInfo, 0, len(a.byID))
|
||||
for _, acc := range a.byID {
|
||||
out = append(out, acc.Info())
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool {
|
||||
if !out[i].Created.Equal(out[j].Created) {
|
||||
return out[i].Created.Before(out[j].Created)
|
||||
}
|
||||
return out[i].ID < out[j].ID
|
||||
})
|
||||
return out
|
||||
}
|
||||
|
||||
// Count renvoie le nombre de comptes.
|
||||
func (a *Accounts) Count() int {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
return len(a.byID)
|
||||
}
|
||||
|
||||
// hasAdmin indique si un administrateur actif existe ; appelé sous mu.
|
||||
func (a *Accounts) hasAdmin() bool {
|
||||
for _, acc := range a.byID {
|
||||
if acc.Role == RoleAdmin && acc.Status == StatusActive {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// NeedsSetup indique qu'aucun administrateur n'existe encore : le premier
|
||||
// compte créé le deviendra.
|
||||
func (a *Accounts) NeedsSetup() bool {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
return !a.hasAdmin()
|
||||
}
|
||||
|
||||
// PendingCount renvoie le nombre d'inscriptions en attente de validation.
|
||||
func (a *Accounts) PendingCount() int {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
n := 0
|
||||
for _, acc := range a.byID {
|
||||
if acc.Status == StatusPending {
|
||||
n++
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func (a *Accounts) byUsername(name string) *Account {
|
||||
for _, acc := range a.byID {
|
||||
if acc.Provider == ProviderLocal && acc.Username == name {
|
||||
return acc
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// --- Création ---------------------------------------------------------------------------
|
||||
|
||||
// NewAccount décrit un compte local à créer.
|
||||
type NewAccount struct {
|
||||
Username string
|
||||
Name string
|
||||
Email string
|
||||
Password string
|
||||
Role string // vide : user (admin si aucun administrateur n'existe)
|
||||
Status string // vide : active
|
||||
}
|
||||
|
||||
func cleanText(s string, max int) (string, bool) {
|
||||
s = strings.Join(strings.Fields(s), " ")
|
||||
return s, utf8.ValidString(s) && utf8.RuneCountInString(s) <= max && !strings.ContainsAny(s, "\x00")
|
||||
}
|
||||
|
||||
// CreateLocal crée un compte local. Tant qu'aucun administrateur n'existe, le
|
||||
// compte créé l'est (et est actif).
|
||||
func (a *Accounts) CreateLocal(n NewAccount) (Account, error) {
|
||||
username := strings.ToLower(strings.TrimSpace(n.Username))
|
||||
if !usernameRe.MatchString(username) || strings.HasPrefix(username, "oidc.") {
|
||||
return Account{}, fmt.Errorf("%w : identifiant de 3 à 32 caractères (a-z, 0-9, point, tiret, tiret bas)", ErrInvalidAccount)
|
||||
}
|
||||
if err := ValidatePassword(n.Password); err != nil {
|
||||
return Account{}, err
|
||||
}
|
||||
name, ok := cleanText(n.Name, maxNameLen)
|
||||
if !ok {
|
||||
return Account{}, fmt.Errorf("%w : nom", ErrInvalidAccount)
|
||||
}
|
||||
if name == "" {
|
||||
name = username
|
||||
}
|
||||
email, ok := cleanText(n.Email, 120)
|
||||
if !ok || (email != "" && (!strings.Contains(email, "@") || strings.ContainsAny(email, " <>\"'"))) {
|
||||
return Account{}, fmt.Errorf("%w : adresse e-mail", ErrInvalidAccount)
|
||||
}
|
||||
hash := hashPassword(n.Password) // hors verrou : calcul lent
|
||||
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if _, exists := a.byID[username]; exists {
|
||||
return Account{}, ErrAccountExists
|
||||
}
|
||||
acc := &Account{ID: username, Username: username, Name: name, Email: email, Provider: ProviderLocal,
|
||||
Role: n.Role, Status: n.Status, Hash: hash, Created: time.Now().UTC().Truncate(time.Second)}
|
||||
if !a.hasAdmin() {
|
||||
acc.Role, acc.Status = RoleAdmin, StatusActive
|
||||
}
|
||||
if acc.Role != RoleAdmin {
|
||||
acc.Role = RoleUser
|
||||
}
|
||||
if acc.Status != StatusPending && acc.Status != StatusDisabled {
|
||||
acc.Status = StatusActive
|
||||
}
|
||||
a.byID[acc.ID] = acc
|
||||
if err := a.save(); err != nil {
|
||||
delete(a.byID, acc.ID)
|
||||
return Account{}, err
|
||||
}
|
||||
return *acc, nil
|
||||
}
|
||||
|
||||
// EnsureAdmin crée l'administrateur local initial (ADMIN_USER / ADMIN_PASSWORD)
|
||||
// s'il n'existe pas ; un compte existant n'est pas modifié.
|
||||
func (a *Accounts) EnsureAdmin(username, password string) error {
|
||||
_, err := a.CreateLocal(NewAccount{Username: username, Name: username, Password: password, Role: RoleAdmin})
|
||||
if errors.Is(err, ErrAccountExists) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// --- Connexion ----------------------------------------------------------------------------
|
||||
|
||||
// Authenticate vérifie un identifiant et un mot de passe locaux.
|
||||
func (a *Accounts) Authenticate(username, password string) (Account, error) {
|
||||
username = strings.ToLower(strings.TrimSpace(username))
|
||||
a.mu.Lock()
|
||||
acc := a.byUsername(username)
|
||||
var hash string
|
||||
if acc != nil {
|
||||
hash = acc.Hash
|
||||
} else {
|
||||
hash = a.dummy
|
||||
}
|
||||
a.mu.Unlock()
|
||||
ok := checkPassword(hash, password) && acc != nil
|
||||
if !ok {
|
||||
return Account{}, ErrBadCredentials
|
||||
}
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
acc = a.byID[acc.ID]
|
||||
if acc == nil {
|
||||
return Account{}, ErrBadCredentials
|
||||
}
|
||||
switch acc.Status {
|
||||
case StatusPending:
|
||||
return *acc, ErrPending
|
||||
case StatusDisabled:
|
||||
return *acc, ErrDisabled
|
||||
}
|
||||
acc.LastLogin = time.Now().UTC().Truncate(time.Second)
|
||||
_ = a.save()
|
||||
return *acc, nil
|
||||
}
|
||||
|
||||
// oidcID construit l'identifiant d'un compte OIDC : l'e-mail s'il existe (il
|
||||
// contient « @ », donc ne peut pas entrer en conflit avec un identifiant local),
|
||||
// sinon « oidc. » suivi du sujet.
|
||||
func oidcID(email, sub string) string {
|
||||
if e := strings.ToLower(strings.TrimSpace(email)); e != "" {
|
||||
return sanitizeID(e)
|
||||
}
|
||||
return "oidc." + sanitizeID(sub)
|
||||
}
|
||||
|
||||
func sanitizeID(raw string) string {
|
||||
var b strings.Builder
|
||||
for _, r := range strings.ToLower(raw) {
|
||||
if r >= 'a' && r <= 'z' || r >= '0' && r <= '9' || strings.ContainsRune("._@+-", r) {
|
||||
b.WriteRune(r)
|
||||
} else {
|
||||
b.WriteByte('_')
|
||||
}
|
||||
}
|
||||
id := strings.TrimLeft(b.String(), ".")
|
||||
if len(id) > 80 {
|
||||
h := sha256.Sum256([]byte(raw))
|
||||
id = id[:60] + "-" + b64.EncodeToString(h[:6])
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
// OIDCPolicy règle la création et la mise à jour des comptes OIDC.
|
||||
type OIDCPolicy struct {
|
||||
AdminGroups []string // groupes dont les membres sont administrateurs
|
||||
AdminEmails []string // adresses dont les titulaires sont administrateurs
|
||||
}
|
||||
|
||||
func (p OIDCPolicy) configured() bool { return len(p.AdminGroups) > 0 || len(p.AdminEmails) > 0 }
|
||||
|
||||
func (p OIDCPolicy) isAdmin(email string, groups []string) bool {
|
||||
for _, e := range p.AdminEmails {
|
||||
if email != "" && strings.EqualFold(strings.TrimSpace(e), email) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
for _, g := range groups {
|
||||
for _, ag := range p.AdminGroups {
|
||||
if g == strings.TrimPrefix(ag, "/") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// UpsertOIDC crée ou met à jour le compte d'une connexion OIDC et renvoie
|
||||
// l'utilisateur de la session. Le compte est créé actif ; il devient
|
||||
// administrateur s'il appartient à OIDC_ADMIN_GROUPS / OIDC_ADMIN_EMAILS, ou
|
||||
// s'il est le premier compte alors qu'aucun administrateur n'existe. Un compte
|
||||
// désactivé ou en attente est refusé (ErrDisabled, ErrPending).
|
||||
func (a *Accounts) UpsertOIDC(u User, groups []string, pol OIDCPolicy) (User, error) {
|
||||
if u.Sub == "" {
|
||||
return User{}, fmt.Errorf("%w : sujet OIDC absent", ErrInvalidAccount)
|
||||
}
|
||||
name, ok := cleanText(u.Name, maxNameLen)
|
||||
if !ok || name == "" {
|
||||
name = u.Sub
|
||||
}
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
var acc *Account
|
||||
for _, c := range a.byID {
|
||||
if c.Provider == ProviderOIDC && c.Sub == u.Sub {
|
||||
acc = c
|
||||
break
|
||||
}
|
||||
}
|
||||
wantAdmin := pol.isAdmin(u.Email, groups)
|
||||
if acc == nil {
|
||||
id := oidcID(u.Email, u.Sub)
|
||||
if _, taken := a.byID[id]; taken { // même e-mail, autre sujet : identifiant distinct
|
||||
id = "oidc." + sanitizeID(u.Sub)
|
||||
}
|
||||
acc = &Account{ID: id, Name: name, Email: u.Email, Provider: ProviderOIDC, Sub: u.Sub,
|
||||
Role: RoleUser, Status: StatusActive, Created: time.Now().UTC().Truncate(time.Second)}
|
||||
if wantAdmin || !a.hasAdmin() {
|
||||
acc.Role = RoleAdmin
|
||||
}
|
||||
a.byID[acc.ID] = acc
|
||||
} else {
|
||||
acc.Name, acc.Email = name, u.Email
|
||||
if pol.configured() {
|
||||
switch {
|
||||
case wantAdmin:
|
||||
acc.Role = RoleAdmin
|
||||
case acc.Role == RoleAdmin && a.otherAdmin(acc.ID):
|
||||
acc.Role = RoleUser
|
||||
}
|
||||
}
|
||||
}
|
||||
switch acc.Status {
|
||||
case StatusPending:
|
||||
return acc.User(), ErrPending
|
||||
case StatusDisabled:
|
||||
return acc.User(), ErrDisabled
|
||||
}
|
||||
acc.LastLogin = time.Now().UTC().Truncate(time.Second)
|
||||
if err := a.save(); err != nil {
|
||||
return User{}, err
|
||||
}
|
||||
return acc.User(), nil
|
||||
}
|
||||
|
||||
// otherAdmin indique si un administrateur actif autre que id existe ; appelé sous mu.
|
||||
func (a *Accounts) otherAdmin(id string) bool {
|
||||
for _, acc := range a.byID {
|
||||
if acc.ID != id && acc.Role == RoleAdmin && acc.Status == StatusActive {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// --- Modification (administration) -------------------------------------------------------
|
||||
|
||||
// Patch décrit les modifications d'un compte (champs nil : inchangés).
|
||||
type Patch struct {
|
||||
Name *string
|
||||
Email *string
|
||||
Role *string
|
||||
Status *string
|
||||
Password *string // comptes locaux seulement
|
||||
}
|
||||
|
||||
// Update modifie un compte. Le dernier administrateur actif ne peut être ni
|
||||
// rétrogradé ni désactivé.
|
||||
func (a *Accounts) Update(id string, p Patch) (Account, error) {
|
||||
var hash string
|
||||
if p.Password != nil {
|
||||
if err := ValidatePassword(*p.Password); err != nil {
|
||||
return Account{}, err
|
||||
}
|
||||
hash = hashPassword(*p.Password)
|
||||
}
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
acc := a.byID[id]
|
||||
if acc == nil {
|
||||
return Account{}, ErrNoAccount
|
||||
}
|
||||
next := *acc
|
||||
if p.Name != nil {
|
||||
n, ok := cleanText(*p.Name, maxNameLen)
|
||||
if !ok || n == "" {
|
||||
return Account{}, fmt.Errorf("%w : nom", ErrInvalidAccount)
|
||||
}
|
||||
next.Name = n
|
||||
}
|
||||
if p.Email != nil && next.Provider == ProviderLocal {
|
||||
e, ok := cleanText(*p.Email, 120)
|
||||
if !ok || (e != "" && (!strings.Contains(e, "@") || strings.ContainsAny(e, " <>\"'"))) {
|
||||
return Account{}, fmt.Errorf("%w : adresse e-mail", ErrInvalidAccount)
|
||||
}
|
||||
next.Email = e
|
||||
}
|
||||
if p.Role != nil {
|
||||
if *p.Role != RoleAdmin && *p.Role != RoleUser {
|
||||
return Account{}, fmt.Errorf("%w : rôle", ErrInvalidAccount)
|
||||
}
|
||||
next.Role = *p.Role
|
||||
}
|
||||
if p.Status != nil {
|
||||
if *p.Status != StatusActive && *p.Status != StatusPending && *p.Status != StatusDisabled {
|
||||
return Account{}, fmt.Errorf("%w : état", ErrInvalidAccount)
|
||||
}
|
||||
next.Status = *p.Status
|
||||
}
|
||||
if p.Password != nil {
|
||||
if next.Provider != ProviderLocal {
|
||||
return Account{}, fmt.Errorf("%w : mot de passe géré par le fournisseur d'identité", ErrInvalidAccount)
|
||||
}
|
||||
next.Hash = hash
|
||||
}
|
||||
wasAdmin := acc.Role == RoleAdmin && acc.Status == StatusActive
|
||||
isAdmin := next.Role == RoleAdmin && next.Status == StatusActive
|
||||
if wasAdmin && !isAdmin && !a.otherAdmin(id) {
|
||||
return Account{}, ErrLastAdmin
|
||||
}
|
||||
*acc = next
|
||||
if err := a.save(); err != nil {
|
||||
return Account{}, err
|
||||
}
|
||||
return *acc, nil
|
||||
}
|
||||
|
||||
// ChangePassword remplace le mot de passe d'un compte local après vérification
|
||||
// de l'ancien.
|
||||
func (a *Accounts) ChangePassword(id, current, next string) error {
|
||||
if err := ValidatePassword(next); err != nil {
|
||||
return err
|
||||
}
|
||||
acc, ok := a.Get(id)
|
||||
if !ok || acc.Provider != ProviderLocal {
|
||||
return ErrNoAccount
|
||||
}
|
||||
if !checkPassword(acc.Hash, current) {
|
||||
return ErrBadCredentials
|
||||
}
|
||||
_, err := a.Update(id, Patch{Password: &next})
|
||||
return err
|
||||
}
|
||||
|
||||
// Delete supprime un compte. Le dernier administrateur actif ne peut l'être.
|
||||
func (a *Accounts) Delete(id string) error {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
acc := a.byID[id]
|
||||
if acc == nil {
|
||||
return ErrNoAccount
|
||||
}
|
||||
if acc.Role == RoleAdmin && acc.Status == StatusActive && !a.otherAdmin(id) {
|
||||
return ErrLastAdmin
|
||||
}
|
||||
delete(a.byID, id)
|
||||
if err := a.save(); err != nil {
|
||||
a.byID[id] = acc
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// --- Limitation des tentatives ------------------------------------------------------------
|
||||
|
||||
// Limiter limite les échecs de connexion : max échecs par clé et par fenêtre.
|
||||
type Limiter struct {
|
||||
mu sync.Mutex
|
||||
max int
|
||||
window time.Duration
|
||||
fails map[string][]time.Time
|
||||
}
|
||||
|
||||
// NewLimiter crée un limiteur.
|
||||
func NewLimiter(max int, window time.Duration) *Limiter {
|
||||
return &Limiter{max: max, window: window, fails: map[string][]time.Time{}}
|
||||
}
|
||||
|
||||
func (l *Limiter) prune(key string, now time.Time) []time.Time {
|
||||
kept := l.fails[key][:0]
|
||||
for _, t := range l.fails[key] {
|
||||
if now.Sub(t) < l.window {
|
||||
kept = append(kept, t)
|
||||
}
|
||||
}
|
||||
if len(kept) == 0 {
|
||||
delete(l.fails, key)
|
||||
} else {
|
||||
l.fails[key] = kept
|
||||
}
|
||||
return kept
|
||||
}
|
||||
|
||||
// Allowed indique si key peut encore tenter une connexion.
|
||||
func (l *Limiter) Allowed(key string) bool {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
return len(l.prune(key, time.Now())) < l.max
|
||||
}
|
||||
|
||||
// Fail enregistre un échec.
|
||||
func (l *Limiter) Fail(key string) {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
now := time.Now()
|
||||
l.prune(key, now)
|
||||
l.fails[key] = append(l.fails[key], now)
|
||||
if len(l.fails) > 10000 { // borne la mémoire
|
||||
for k := range l.fails {
|
||||
if len(l.prune(k, now)) == 0 {
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Reset efface les échecs de key (connexion réussie).
|
||||
func (l *Limiter) Reset(key string) {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
delete(l.fails, key)
|
||||
}
|
||||
@@ -0,0 +1,473 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/cookiejar"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func init() { pbkdf2Iter = 1000 } // tests rapides
|
||||
|
||||
func newAccounts(t *testing.T) *Accounts {
|
||||
t.Helper()
|
||||
a, err := OpenAccounts(t.TempDir())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return a
|
||||
}
|
||||
|
||||
func TestFirstAccountIsAdmin(t *testing.T) {
|
||||
a := newAccounts(t)
|
||||
if !a.NeedsSetup() {
|
||||
t.Fatal("NeedsSetup")
|
||||
}
|
||||
first, err := a.CreateLocal(NewAccount{Username: "Alice", Password: "un-mot-de-passe", Status: StatusPending})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if first.Role != RoleAdmin || first.Status != StatusActive || first.ID != "alice" {
|
||||
t.Errorf("premier compte = %+v", first)
|
||||
}
|
||||
second, _ := a.CreateLocal(NewAccount{Username: "bob", Password: "un-mot-de-passe", Status: StatusPending})
|
||||
if second.Role != RoleUser || second.Status != StatusPending {
|
||||
t.Errorf("second compte = %+v", second)
|
||||
}
|
||||
if a.NeedsSetup() || a.PendingCount() != 1 {
|
||||
t.Error("état après création")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateLocalValidation(t *testing.T) {
|
||||
a := newAccounts(t)
|
||||
for _, n := range []NewAccount{
|
||||
{Username: "ab", Password: "un-mot-de-passe"}, // trop court
|
||||
{Username: "Bob Dupont", Password: "un-mot-de-passe"}, // espace
|
||||
{Username: "oidc.x", Password: "un-mot-de-passe"}, // préfixe réservé
|
||||
{Username: "bob@example.org", Password: "un-mot-de-passe"}, // @ réservé aux comptes OIDC
|
||||
{Username: "bob", Password: "court"}, // mot de passe trop court
|
||||
{Username: "bob", Password: "un-mot-de-passe", Email: "x"}, // e-mail invalide
|
||||
{Username: "bob", Password: strings.Repeat("x", 300)}, // mot de passe trop long
|
||||
{Username: ".hidden", Password: "un-mot-de-passe"}, // caché
|
||||
{Username: "bob", Password: "un-mot-de-passe", Name: "a\x00"}, // nom invalide
|
||||
} {
|
||||
if _, err := a.CreateLocal(n); !errors.Is(err, ErrInvalidAccount) {
|
||||
t.Errorf("CreateLocal(%+v) = %v", n, err)
|
||||
}
|
||||
}
|
||||
if _, err := a.CreateLocal(NewAccount{Username: "bob", Password: "un-mot-de-passe"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := a.CreateLocal(NewAccount{Username: "BOB", Password: "un-mot-de-passe"}); !errors.Is(err, ErrAccountExists) {
|
||||
t.Errorf("doublon : %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthenticate(t *testing.T) {
|
||||
a := newAccounts(t)
|
||||
_, _ = a.CreateLocal(NewAccount{Username: "alice", Password: "mot-de-passe-1"})
|
||||
_, _ = a.CreateLocal(NewAccount{Username: "bob", Password: "mot-de-passe-2", Status: StatusPending})
|
||||
if _, err := a.Authenticate("Alice", "mot-de-passe-1"); err != nil {
|
||||
t.Errorf("connexion : %v", err)
|
||||
}
|
||||
if _, err := a.Authenticate("alice", "faux"); !errors.Is(err, ErrBadCredentials) {
|
||||
t.Errorf("mauvais mot de passe : %v", err)
|
||||
}
|
||||
if _, err := a.Authenticate("inconnu", "mot-de-passe-1"); !errors.Is(err, ErrBadCredentials) {
|
||||
t.Errorf("inconnu : %v", err)
|
||||
}
|
||||
if _, err := a.Authenticate("bob", "mot-de-passe-2"); !errors.Is(err, ErrPending) {
|
||||
t.Errorf("en attente : %v", err)
|
||||
}
|
||||
// Mauvais mot de passe d'un compte en attente : pas de fuite d'état.
|
||||
if _, err := a.Authenticate("bob", "faux"); !errors.Is(err, ErrBadCredentials) {
|
||||
t.Errorf("fuite d'état : %v", err)
|
||||
}
|
||||
disabled := StatusDisabled
|
||||
_, _ = a.Update("bob", Patch{Status: &disabled})
|
||||
if _, err := a.Authenticate("bob", "mot-de-passe-2"); !errors.Is(err, ErrDisabled) {
|
||||
t.Errorf("désactivé : %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPersistenceAndFileMode(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
a, _ := OpenAccounts(dir)
|
||||
_, _ = a.CreateLocal(NewAccount{Username: "alice", Password: "mot-de-passe-1"})
|
||||
b, err := OpenAccounts(dir)
|
||||
if err != nil || b.Count() != 1 {
|
||||
t.Fatalf("rechargement : %v %d", err, b.Count())
|
||||
}
|
||||
if _, err := b.Authenticate("alice", "mot-de-passe-1"); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLastAdminProtected(t *testing.T) {
|
||||
a := newAccounts(t)
|
||||
_, _ = a.CreateLocal(NewAccount{Username: "alice", Password: "mot-de-passe-1"}) // admin
|
||||
user, disabled := RoleUser, StatusDisabled
|
||||
if _, err := a.Update("alice", Patch{Role: &user}); !errors.Is(err, ErrLastAdmin) {
|
||||
t.Errorf("rétrogradation : %v", err)
|
||||
}
|
||||
if _, err := a.Update("alice", Patch{Status: &disabled}); !errors.Is(err, ErrLastAdmin) {
|
||||
t.Errorf("désactivation : %v", err)
|
||||
}
|
||||
if err := a.Delete("alice"); !errors.Is(err, ErrLastAdmin) {
|
||||
t.Errorf("suppression : %v", err)
|
||||
}
|
||||
admin := RoleAdmin
|
||||
_, _ = a.CreateLocal(NewAccount{Username: "bob", Password: "mot-de-passe-2"})
|
||||
_, _ = a.Update("bob", Patch{Role: &admin})
|
||||
if _, err := a.Update("alice", Patch{Role: &user}); err != nil {
|
||||
t.Errorf("rétrogradation avec un autre admin : %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChangePassword(t *testing.T) {
|
||||
a := newAccounts(t)
|
||||
_, _ = a.CreateLocal(NewAccount{Username: "alice", Password: "ancien-mot-de-passe"})
|
||||
if err := a.ChangePassword("alice", "faux", "nouveau-mot-de-passe"); !errors.Is(err, ErrBadCredentials) {
|
||||
t.Errorf("ancien faux : %v", err)
|
||||
}
|
||||
if err := a.ChangePassword("alice", "ancien-mot-de-passe", "court"); !errors.Is(err, ErrInvalidAccount) {
|
||||
t.Errorf("nouveau trop court : %v", err)
|
||||
}
|
||||
if err := a.ChangePassword("alice", "ancien-mot-de-passe", "nouveau-mot-de-passe"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := a.Authenticate("alice", "nouveau-mot-de-passe"); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
if _, err := a.Authenticate("alice", "ancien-mot-de-passe"); err == nil {
|
||||
t.Error("ancien mot de passe encore valable")
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpsertOIDC(t *testing.T) {
|
||||
a := newAccounts(t)
|
||||
pol := OIDCPolicy{AdminGroups: []string{"admins"}}
|
||||
u1, err := a.UpsertOIDC(User{Sub: "s1", Name: "Zoé", Email: "Zoe@Example.org"}, []string{"users"}, pol)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Premier compte : administrateur même hors du groupe (aucun admin n'existait).
|
||||
if u1.ID != "zoe@example.org" || u1.Role != RoleAdmin || u1.Provider != ProviderOIDC {
|
||||
t.Errorf("premier = %+v", u1)
|
||||
}
|
||||
u2, _ := a.UpsertOIDC(User{Sub: "s2", Name: "Max", Email: "max@example.org"}, []string{"users"}, pol)
|
||||
if u2.Role != RoleUser {
|
||||
t.Errorf("second = %+v", u2)
|
||||
}
|
||||
// Promotion par groupe, puis rétrogradation quand il en sort.
|
||||
u2, _ = a.UpsertOIDC(User{Sub: "s2", Name: "Max", Email: "max@example.org"}, []string{"admins"}, pol)
|
||||
if u2.Role != RoleAdmin {
|
||||
t.Errorf("promotion = %+v", u2)
|
||||
}
|
||||
u2, _ = a.UpsertOIDC(User{Sub: "s2", Name: "Max", Email: "max@example.org"}, nil, pol)
|
||||
if u2.Role != RoleUser {
|
||||
t.Errorf("rétrogradation = %+v", u2)
|
||||
}
|
||||
// Même sujet, nouvel e-mail : même compte.
|
||||
u3, _ := a.UpsertOIDC(User{Sub: "s2", Name: "Max B", Email: "max@autre.org"}, nil, pol)
|
||||
if u3.ID != u2.ID || u3.Name != "Max B" {
|
||||
t.Errorf("identité : %+v", u3)
|
||||
}
|
||||
// Sans e-mail : identifiant « oidc.<sub> », qui ne peut pas être un identifiant local.
|
||||
u4, _ := a.UpsertOIDC(User{Sub: "S/4", Name: "Sans mail"}, nil, pol)
|
||||
if !strings.HasPrefix(u4.ID, "oidc.") {
|
||||
t.Errorf("sans e-mail = %+v", u4)
|
||||
}
|
||||
if _, err := a.CreateLocal(NewAccount{Username: u4.ID, Password: "mot-de-passe-1"}); err == nil {
|
||||
t.Error("identifiant local en collision avec un compte OIDC")
|
||||
}
|
||||
// Même e-mail, autre sujet : pas de fusion (prise de contrôle).
|
||||
u5, _ := a.UpsertOIDC(User{Sub: "autre", Name: "Usurpateur", Email: "zoe@example.org"}, nil, pol)
|
||||
if u5.ID == u1.ID {
|
||||
t.Error("deux sujets OIDC partagent un compte")
|
||||
}
|
||||
// Désactivation.
|
||||
disabled := StatusDisabled
|
||||
_, _ = a.Update(u2.ID, Patch{Status: &disabled})
|
||||
if _, err := a.UpsertOIDC(User{Sub: "s2", Name: "Max", Email: "max@autre.org"}, nil, pol); !errors.Is(err, ErrDisabled) {
|
||||
t.Errorf("désactivé : %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLimiter(t *testing.T) {
|
||||
l := NewLimiter(3, 50*time.Millisecond)
|
||||
for i := 0; i < 3; i++ {
|
||||
if !l.Allowed("k") {
|
||||
t.Fatal("bloqué trop tôt")
|
||||
}
|
||||
l.Fail("k")
|
||||
}
|
||||
if l.Allowed("k") {
|
||||
t.Error("pas bloqué")
|
||||
}
|
||||
if !l.Allowed("autre") {
|
||||
t.Error("autre clé bloquée")
|
||||
}
|
||||
time.Sleep(60 * time.Millisecond)
|
||||
if !l.Allowed("k") {
|
||||
t.Error("fenêtre non expirée")
|
||||
}
|
||||
l.Fail("k")
|
||||
l.Reset("k")
|
||||
if !l.Allowed("k") {
|
||||
t.Error("Reset")
|
||||
}
|
||||
}
|
||||
|
||||
// --- Flux HTTP (sans ouvrir de port) -------------------------------------------------
|
||||
|
||||
type browser struct {
|
||||
t *testing.T
|
||||
h http.Handler
|
||||
cookies map[string]*http.Cookie
|
||||
}
|
||||
|
||||
func newBrowser(t *testing.T, h http.Handler) *browser {
|
||||
return &browser{t: t, h: h, cookies: map[string]*http.Cookie{}}
|
||||
}
|
||||
|
||||
func (b *browser) do(method, path, body string) *httptest.ResponseRecorder {
|
||||
r := httptest.NewRequest(method, path, strings.NewReader(body))
|
||||
if body != "" {
|
||||
r.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
for _, c := range b.cookies {
|
||||
r.AddCookie(c)
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
b.h.ServeHTTP(w, r)
|
||||
for _, c := range w.Result().Cookies() {
|
||||
if c.MaxAge < 0 {
|
||||
delete(b.cookies, c.Name)
|
||||
} else {
|
||||
b.cookies[c.Name] = c
|
||||
}
|
||||
}
|
||||
return w
|
||||
}
|
||||
|
||||
func testAuth(t *testing.T, reg string) (*Auth, http.Handler) {
|
||||
t.Helper()
|
||||
acc := newAccounts(t)
|
||||
a := New(&Auth{
|
||||
Accounts: acc,
|
||||
Sessions: NewSessions([]byte("0123456789abcdef0123456789abcdef"), time.Hour, false),
|
||||
Local: true,
|
||||
Registration: func() string { return reg },
|
||||
})
|
||||
mux := http.NewServeMux()
|
||||
a.Register(mux)
|
||||
mux.HandleFunc("GET /api/whoami", func(w http.ResponseWriter, r *http.Request) {
|
||||
u := UserFrom(r.Context())
|
||||
_, _ = w.Write([]byte(u.ID + ":" + u.Role))
|
||||
})
|
||||
mux.HandleFunc("GET /api/open", func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte("ouvert")) })
|
||||
mux.HandleFunc("GET /", func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte("<html>spa</html>")) })
|
||||
return a, a.Middleware(mux, func(p string) bool { return p == "/api/open" })
|
||||
}
|
||||
|
||||
func TestRegistrationClosedAllowsOnlySetup(t *testing.T) {
|
||||
_, h := testAuth(t, "closed")
|
||||
b := newBrowser(t, h)
|
||||
// Premier compte : accepté malgré « closed » (installation), connecté d'office.
|
||||
w := b.do("POST", "/auth/local/register", `{"username":"admin","password":"mot-de-passe-1"}`)
|
||||
if w.Code != 201 {
|
||||
t.Fatalf("installation : %d %s", w.Code, w.Body)
|
||||
}
|
||||
if got := b.do("GET", "/api/whoami", "").Body.String(); got != "admin:admin" {
|
||||
t.Errorf("whoami = %q", got)
|
||||
}
|
||||
// Ensuite, fermé.
|
||||
b2 := newBrowser(t, h)
|
||||
if w := b2.do("POST", "/auth/local/register", `{"username":"bob","password":"mot-de-passe-1"}`); w.Code != 403 {
|
||||
t.Errorf("inscription fermée : %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistrationApprovalFlow(t *testing.T) {
|
||||
a, h := testAuth(t, "approval")
|
||||
_, _ = a.Accounts.CreateLocal(NewAccount{Username: "root", Password: "mot-de-passe-0"})
|
||||
b := newBrowser(t, h)
|
||||
w := b.do("POST", "/auth/local/register", `{"username":"bob","name":"Bob","password":"mot-de-passe-1"}`)
|
||||
if w.Code != 202 || len(b.cookies) != 0 {
|
||||
t.Fatalf("inscription : %d %s %v", w.Code, w.Body, b.cookies)
|
||||
}
|
||||
w = b.do("POST", "/auth/local/login", `{"username":"bob","password":"mot-de-passe-1"}`)
|
||||
if w.Code != 403 || !strings.Contains(w.Body.String(), `"pending"`) {
|
||||
t.Errorf("connexion en attente : %d %s", w.Code, w.Body)
|
||||
}
|
||||
if b.do("GET", "/api/whoami", "").Code != 401 {
|
||||
t.Error("accès sans session")
|
||||
}
|
||||
active := StatusActive
|
||||
_, _ = a.Accounts.Update("bob", Patch{Status: &active})
|
||||
if w = b.do("POST", "/auth/local/login", `{"username":"bob","password":"mot-de-passe-1"}`); w.Code != 200 {
|
||||
t.Fatalf("connexion : %d %s", w.Code, w.Body)
|
||||
}
|
||||
if got := b.do("GET", "/api/whoami", "").Body.String(); got != "bob:user" {
|
||||
t.Errorf("whoami = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistrationOpenAutoLogin(t *testing.T) {
|
||||
a, h := testAuth(t, "open")
|
||||
_, _ = a.Accounts.CreateLocal(NewAccount{Username: "root", Password: "mot-de-passe-0"})
|
||||
b := newBrowser(t, h)
|
||||
if w := b.do("POST", "/auth/local/register", `{"username":"carl","password":"mot-de-passe-1"}`); w.Code != 201 {
|
||||
t.Fatalf("%d %s", w.Code, w.Body)
|
||||
}
|
||||
if got := b.do("GET", "/api/whoami", "").Body.String(); got != "carl:user" {
|
||||
t.Errorf("whoami = %q", got)
|
||||
}
|
||||
if w := b.do("POST", "/auth/local/register", `{"username":"carl","password":"mot-de-passe-1"}`); w.Code != 409 {
|
||||
t.Errorf("doublon : %d", w.Code)
|
||||
}
|
||||
if w := b.do("POST", "/auth/local/register", `{"username":"x","password":"mot-de-passe-1"}`); w.Code != 400 {
|
||||
t.Errorf("identifiant invalide : %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistrationThrottle(t *testing.T) {
|
||||
a, h := testAuth(t, "open")
|
||||
_, _ = a.Accounts.CreateLocal(NewAccount{Username: "root", Password: "mot-de-passe-0"})
|
||||
last := 0
|
||||
for i := 0; i < 8; i++ {
|
||||
b := newBrowser(t, h)
|
||||
w := b.do("POST", "/auth/local/register", `{"username":"user`+string(rune('a'+i))+`x","password":"mot-de-passe-1"}`)
|
||||
last = w.Code
|
||||
}
|
||||
if last != 429 {
|
||||
t.Errorf("après 8 inscriptions depuis la même adresse : %d", last)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoginThrottleAndSessionRules(t *testing.T) {
|
||||
a, h := testAuth(t, "closed")
|
||||
_, _ = a.Accounts.CreateLocal(NewAccount{Username: "alice", Password: "mot-de-passe-1"})
|
||||
b := newBrowser(t, h)
|
||||
for i := 0; i < 10; i++ {
|
||||
if w := b.do("POST", "/auth/local/login", `{"username":"alice","password":"faux"}`); w.Code != 401 {
|
||||
t.Fatalf("essai %d : %d", i, w.Code)
|
||||
}
|
||||
}
|
||||
if w := b.do("POST", "/auth/local/login", `{"username":"alice","password":"mot-de-passe-1"}`); w.Code != 429 {
|
||||
t.Errorf("après 10 échecs : %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMiddlewareRoutesAndSessionRevocation(t *testing.T) {
|
||||
a, h := testAuth(t, "closed")
|
||||
_, _ = a.Accounts.CreateLocal(NewAccount{Username: "alice", Password: "mot-de-passe-1"})
|
||||
_, _ = a.Accounts.CreateLocal(NewAccount{Username: "bob", Password: "mot-de-passe-2"})
|
||||
b := newBrowser(t, h)
|
||||
// Sans session : API refusée, route publique ouverte, navigation = application.
|
||||
if w := b.do("GET", "/api/whoami", ""); w.Code != 401 || w.Header().Get(LoginHeader) != "" {
|
||||
t.Errorf("API : %d %v", w.Code, w.Header())
|
||||
}
|
||||
if w := b.do("GET", "/api/open", ""); w.Code != 200 {
|
||||
t.Errorf("public : %d", w.Code)
|
||||
}
|
||||
if w := b.do("GET", "/", ""); w.Code != 200 || !strings.Contains(w.Body.String(), "spa") {
|
||||
t.Errorf("navigation : %d %s", w.Code, w.Body)
|
||||
}
|
||||
if w := b.do("POST", "/api/whoami", ""); w.Code != 401 {
|
||||
t.Errorf("POST sans session : %d", w.Code)
|
||||
}
|
||||
b.do("POST", "/auth/local/login", `{"username":"bob","password":"mot-de-passe-2"}`)
|
||||
if got := b.do("GET", "/api/whoami", "").Body.String(); got != "bob:user" {
|
||||
t.Fatalf("whoami = %q", got)
|
||||
}
|
||||
// Un compte désactivé perd sa session tout de suite.
|
||||
disabled := StatusDisabled
|
||||
_, _ = a.Accounts.Update("bob", Patch{Status: &disabled})
|
||||
if w := b.do("GET", "/api/whoami", ""); w.Code != 401 {
|
||||
t.Errorf("session d'un compte désactivé : %d", w.Code)
|
||||
}
|
||||
// Un compte supprimé aussi.
|
||||
b2 := newBrowser(t, h)
|
||||
b2.do("POST", "/auth/local/login", `{"username":"alice","password":"mot-de-passe-1"}`)
|
||||
_, _ = a.Accounts.CreateLocal(NewAccount{Username: "carl", Password: "mot-de-passe-3", Role: RoleAdmin})
|
||||
_ = a.Accounts.Delete("alice")
|
||||
if w := b2.do("GET", "/api/whoami", ""); w.Code != 401 {
|
||||
t.Errorf("session d'un compte supprimé : %d", w.Code)
|
||||
}
|
||||
// Un cookie falsifié est refusé.
|
||||
b3 := newBrowser(t, h)
|
||||
b3.cookies["upandown_session"] = &http.Cookie{Name: "upandown_session", Value: "eyJpZCI6ImFkbWluIn0.AAAA"}
|
||||
if w := b3.do("GET", "/api/whoami", ""); w.Code != 401 {
|
||||
t.Errorf("cookie falsifié : %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLogoutClearsSession(t *testing.T) {
|
||||
a, h := testAuth(t, "closed")
|
||||
_, _ = a.Accounts.CreateLocal(NewAccount{Username: "alice", Password: "mot-de-passe-1"})
|
||||
b := newBrowser(t, h)
|
||||
b.do("POST", "/auth/local/login", `{"username":"alice","password":"mot-de-passe-1"}`)
|
||||
if w := b.do("GET", "/auth/logout", ""); w.Code != 303 {
|
||||
t.Errorf("logout : %d", w.Code)
|
||||
}
|
||||
if w := b.do("GET", "/api/whoami", ""); w.Code != 401 {
|
||||
t.Errorf("après logout : %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOIDCLoginCreatesAccountAndHonoursStatus(t *testing.T) {
|
||||
idp := newIdP(t, "RS256")
|
||||
acc := newAccounts(t)
|
||||
sessions := NewSessions([]byte("0123456789abcdef0123456789abcdef"), time.Hour, false)
|
||||
o, err := NewOIDC(context.Background(), Config{
|
||||
Issuer: idp.srv.URL, ClientID: "excalicloud", ClientSecret: idp.secret,
|
||||
Secret: []byte("0123456789abcdef0123456789abcdef"), Client: testNet.client(), Sessions: sessions,
|
||||
Provision: func(u User, g []string) (User, error) { return acc.UpsertOIDC(u, g, OIDCPolicy{}) },
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
a := New(&Auth{Accounts: acc, Sessions: sessions, OIDC: o})
|
||||
mux := http.NewServeMux()
|
||||
a.Register(mux)
|
||||
mux.HandleFunc("GET /api/whoami", func(w http.ResponseWriter, r *http.Request) {
|
||||
u := UserFrom(r.Context())
|
||||
_, _ = w.Write([]byte(u.ID + ":" + u.Role + ":" + u.Provider))
|
||||
})
|
||||
mux.HandleFunc("GET /", func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte("app")) })
|
||||
srv := testNet.serve("app", a.Middleware(mux, func(string) bool { return false }))
|
||||
jar, _ := cookiejar.New(nil)
|
||||
c := &http.Client{Jar: jar, Transport: testNet}
|
||||
|
||||
if res, body := get(t, c, srv.URL+"/api/whoami"); res.StatusCode != 401 || res.Header.Get(LoginHeader) != "/auth/login" {
|
||||
t.Fatalf("OIDC seul, sans session : %d %q", res.StatusCode, body)
|
||||
}
|
||||
if res, body := get(t, c, srv.URL+"/auth/login"); res.StatusCode != 200 || body != "app" {
|
||||
t.Fatalf("connexion : %d %q", res.StatusCode, body)
|
||||
}
|
||||
if _, body := get(t, c, srv.URL+"/api/whoami"); body != "cedric@example.org:admin:oidc" {
|
||||
t.Errorf("whoami = %q", body)
|
||||
}
|
||||
if got, ok := acc.Get("cedric@example.org"); !ok || got.Sub != "u-42" {
|
||||
t.Errorf("compte non créé : %+v", got)
|
||||
}
|
||||
// Désactivation : la session tombe, la reconnexion est refusée avec un message clair.
|
||||
id := "cedric@example.org"
|
||||
admin, disabled := RoleAdmin, StatusDisabled
|
||||
_, _ = acc.CreateLocal(NewAccount{Username: "backup", Password: "mot-de-passe-1", Role: admin})
|
||||
_, _ = acc.Update(id, Patch{Status: &disabled})
|
||||
if res, _ := get(t, c, srv.URL+"/api/whoami"); res.StatusCode != 401 {
|
||||
t.Errorf("session d'un compte désactivé : %d", res.StatusCode)
|
||||
}
|
||||
res, body := get(t, c, srv.URL+"/auth/login")
|
||||
if res.StatusCode != 403 || !strings.Contains(body, "désactivé") {
|
||||
t.Errorf("reconnexion refusée : %d %.80s", res.StatusCode, body)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Auth réunit l'authentification locale (comptes, inscription) et OIDC derrière
|
||||
// une même session : cookie signé, vérifié à chaque requête contre l'état du
|
||||
// compte (désactivé, supprimé, rôle modifié : effet immédiat).
|
||||
//
|
||||
// POST /auth/local/login {"username","password"}
|
||||
// POST /auth/local/register {"username","name","email","password"}
|
||||
// GET /auth/login connexion OIDC (si activée)
|
||||
// GET /auth/logout déconnexion (propagée au fournisseur OIDC)
|
||||
type Auth struct {
|
||||
Accounts *Accounts
|
||||
Sessions *Sessions
|
||||
OIDC *OIDC // nil : OIDC désactivé
|
||||
Local bool // comptes locaux activés
|
||||
// Registration renvoie le mode d'inscription courant : closed, approval ou open.
|
||||
Registration func() string
|
||||
// OIDCName : libellé du bouton de connexion OIDC.
|
||||
OIDCName string
|
||||
|
||||
logins *Limiter
|
||||
regs *Limiter
|
||||
}
|
||||
|
||||
// New prépare l'authentification ; Accounts et Sessions sont obligatoires.
|
||||
func New(a *Auth) *Auth {
|
||||
a.logins = NewLimiter(10, 15*time.Minute)
|
||||
a.regs = NewLimiter(5, time.Hour)
|
||||
if a.Registration == nil {
|
||||
a.Registration = func() string { return "closed" }
|
||||
}
|
||||
return a
|
||||
}
|
||||
|
||||
// OnlyOIDC indique que la connexion passe uniquement par le fournisseur OIDC.
|
||||
func (a *Auth) OnlyOIDC() bool { return a.OIDC != nil && !a.Local }
|
||||
|
||||
// Register ajoute les routes /auth/*.
|
||||
func (a *Auth) Register(mux *http.ServeMux) {
|
||||
if a.OIDC != nil {
|
||||
a.OIDC.RegisterLogin(mux)
|
||||
}
|
||||
if a.Local {
|
||||
mux.HandleFunc("POST /auth/local/login", a.localLogin)
|
||||
mux.HandleFunc("POST /auth/local/register", a.localRegister)
|
||||
}
|
||||
mux.HandleFunc("GET /auth/logout", a.logout)
|
||||
mux.HandleFunc("POST /auth/logout", a.logout)
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, status int, v any) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
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})
|
||||
}
|
||||
|
||||
// clientIP : adresse du client. Derrière un reverse proxy, l'entrée la plus à
|
||||
// droite de X-Forwarded-For est celle qu'il a ajoutée.
|
||||
func clientIP(r *http.Request) string {
|
||||
if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
|
||||
parts := strings.Split(xff, ",")
|
||||
if ip := strings.TrimSpace(parts[len(parts)-1]); ip != "" {
|
||||
return ip
|
||||
}
|
||||
}
|
||||
host, _, err := net.SplitHostPort(r.RemoteAddr)
|
||||
if err != nil {
|
||||
return r.RemoteAddr
|
||||
}
|
||||
return host
|
||||
}
|
||||
|
||||
type credentials struct {
|
||||
Username string `json:"username"`
|
||||
Name string `json:"name"`
|
||||
Email string `json:"email"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
func decodeJSON(w http.ResponseWriter, r *http.Request, v any) bool {
|
||||
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 16<<10)).Decode(v); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "requête JSON invalide")
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (a *Auth) localLogin(w http.ResponseWriter, r *http.Request) {
|
||||
var c credentials
|
||||
if !decodeJSON(w, r, &c) {
|
||||
return
|
||||
}
|
||||
userKey, ipKey := "u:"+strings.ToLower(strings.TrimSpace(c.Username)), "ip:"+clientIP(r)
|
||||
if !a.logins.Allowed(userKey) || !a.logins.Allowed(ipKey) {
|
||||
w.Header().Set("Retry-After", "900")
|
||||
writeErr(w, http.StatusTooManyRequests, "trop de tentatives : réessayer dans quelques minutes")
|
||||
return
|
||||
}
|
||||
acc, err := a.Accounts.Authenticate(c.Username, c.Password)
|
||||
switch err {
|
||||
case nil:
|
||||
case ErrBadCredentials:
|
||||
a.logins.Fail(userKey)
|
||||
a.logins.Fail(ipKey)
|
||||
writeErr(w, http.StatusUnauthorized, err.Error())
|
||||
return
|
||||
case ErrPending, ErrDisabled:
|
||||
writeJSON(w, http.StatusForbidden, map[string]string{"error": err.Error(), "code": codeOf(err)})
|
||||
return
|
||||
default:
|
||||
slog.Error("connexion locale", "err", err)
|
||||
writeErr(w, http.StatusInternalServerError, "erreur interne")
|
||||
return
|
||||
}
|
||||
a.logins.Reset(userKey)
|
||||
if err := a.Sessions.Start(w, r, acc.User()); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "erreur interne")
|
||||
return
|
||||
}
|
||||
slog.Info("connexion locale", "user", acc.ID)
|
||||
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
|
||||
}
|
||||
|
||||
func codeOf(err error) string {
|
||||
if err == ErrPending {
|
||||
return "pending"
|
||||
}
|
||||
return "disabled"
|
||||
}
|
||||
|
||||
func (a *Auth) localRegister(w http.ResponseWriter, r *http.Request) {
|
||||
var c credentials
|
||||
if !decodeJSON(w, r, &c) {
|
||||
return
|
||||
}
|
||||
setup := a.Accounts.NeedsSetup() // premier compte : administrateur, même si les inscriptions sont fermées
|
||||
mode := a.Registration()
|
||||
if mode == "closed" && !setup {
|
||||
writeErr(w, http.StatusForbidden, "les inscriptions sont fermées")
|
||||
return
|
||||
}
|
||||
ipKey := "reg:" + clientIP(r)
|
||||
if !setup && !a.regs.Allowed(ipKey) {
|
||||
w.Header().Set("Retry-After", "3600")
|
||||
writeErr(w, http.StatusTooManyRequests, "trop d'inscriptions depuis cette adresse")
|
||||
return
|
||||
}
|
||||
status := StatusActive
|
||||
if mode == "approval" {
|
||||
status = StatusPending
|
||||
}
|
||||
acc, err := a.Accounts.CreateLocal(NewAccount{Username: c.Username, Name: c.Name, Email: c.Email,
|
||||
Password: c.Password, Status: status})
|
||||
if err != nil {
|
||||
code := http.StatusBadRequest
|
||||
if err == ErrAccountExists {
|
||||
code = http.StatusConflict
|
||||
}
|
||||
writeErr(w, code, err.Error())
|
||||
return
|
||||
}
|
||||
if !setup {
|
||||
a.regs.Fail(ipKey)
|
||||
}
|
||||
slog.Info("inscription", "user", acc.ID, "status", acc.Status, "role", acc.Role)
|
||||
if acc.Status == StatusPending {
|
||||
writeJSON(w, http.StatusAccepted, map[string]string{"status": StatusPending})
|
||||
return
|
||||
}
|
||||
if err := a.Sessions.Start(w, r, acc.User()); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "erreur interne")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, map[string]string{"status": StatusActive})
|
||||
}
|
||||
|
||||
func (a *Auth) logout(w http.ResponseWriter, r *http.Request) {
|
||||
if s, ok := a.Sessions.Get(r); ok && s.Provider == ProviderOIDC && a.OIDC != nil {
|
||||
a.OIDC.logout(w, r)
|
||||
return
|
||||
}
|
||||
a.Sessions.Clear(w, r)
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
http.Redirect(w, r, "/", http.StatusSeeOther)
|
||||
}
|
||||
|
||||
// current renvoie l'utilisateur de la session : le compte doit exister et être
|
||||
// actif ; son rôle est celui du compte. La session est prolongée passée la
|
||||
// moitié de sa durée.
|
||||
func (a *Auth) current(w http.ResponseWriter, r *http.Request) (*User, bool) {
|
||||
s, ok := a.Sessions.Get(r)
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
acc, ok := a.Accounts.Get(s.ID)
|
||||
if !ok || acc.Status != StatusActive {
|
||||
a.Sessions.Clear(w, r)
|
||||
return nil, false
|
||||
}
|
||||
u := acc.User()
|
||||
if time.Until(time.Unix(s.Exp, 0)) < a.Sessions.TTL/2 {
|
||||
_ = a.Sessions.Start(w, r, u)
|
||||
}
|
||||
return &u, true
|
||||
}
|
||||
|
||||
// Middleware exige une session sauf pour /auth/* et les chemins publics. Sans
|
||||
// session : l'API répond 401 ; une navigation reçoit l'application, qui affiche
|
||||
// la page de connexion (ou, avec OIDC seul, est renvoyée vers le fournisseur).
|
||||
func (a *Auth) Middleware(next http.Handler, public func(string) bool) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
p := r.URL.Path
|
||||
if strings.HasPrefix(p, "/auth/") || public(p) {
|
||||
if u, ok := a.current(w, r); ok { // identité disponible sur les routes publiques (ex. /api/me)
|
||||
r = r.WithContext(WithUser(r.Context(), u))
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
u, ok := a.current(w, r)
|
||||
if ok {
|
||||
next.ServeHTTP(w, r.WithContext(WithUser(r.Context(), u)))
|
||||
return
|
||||
}
|
||||
if strings.HasPrefix(p, "/api/") || r.Method != http.MethodGet {
|
||||
if a.OnlyOIDC() {
|
||||
w.Header().Set(LoginHeader, "/auth/login")
|
||||
}
|
||||
writeErr(w, http.StatusUnauthorized, "connexion nécessaire")
|
||||
return
|
||||
}
|
||||
if a.OnlyOIDC() {
|
||||
loginRedirect(w)
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
// UserContext renvoie ctx portant l'utilisateur u (jetons d'API).
|
||||
func UserContext(ctx context.Context, u *User) context.Context { return WithUser(ctx, u) }
|
||||
@@ -0,0 +1,379 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto"
|
||||
"crypto/ecdsa"
|
||||
"crypto/elliptic"
|
||||
"crypto/hmac"
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"crypto/sha256"
|
||||
"crypto/tls"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"math/big"
|
||||
"net/http"
|
||||
"net/http/cookiejar"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// memNet est un « réseau » en mémoire : chaque hôte https est servi par un
|
||||
// http.Handler, sans ouvrir de port (les tests tournent aussi sous un bac à
|
||||
// sable qui interdit l'écoute locale).
|
||||
type memNet struct {
|
||||
hosts map[string]http.Handler
|
||||
n int
|
||||
}
|
||||
|
||||
var testNet = &memNet{hosts: map[string]http.Handler{}}
|
||||
|
||||
type memServer struct{ URL string }
|
||||
|
||||
// serve enregistre h sous un nouveau nom d'hôte et renvoie son URL.
|
||||
func (m *memNet) serve(prefix string, h http.Handler) *memServer {
|
||||
m.n++
|
||||
host := fmt.Sprintf("%s%d.test", prefix, m.n)
|
||||
m.hosts[host] = h
|
||||
return &memServer{URL: "https://" + host}
|
||||
}
|
||||
|
||||
func (m *memNet) RoundTrip(req *http.Request) (*http.Response, error) {
|
||||
h := m.hosts[req.URL.Host]
|
||||
if h == nil {
|
||||
return nil, fmt.Errorf("hôte inconnu : %s", req.URL.Host)
|
||||
}
|
||||
r := req.Clone(req.Context())
|
||||
r.RequestURI = req.URL.RequestURI()
|
||||
if r.Host == "" {
|
||||
r.Host = req.URL.Host
|
||||
}
|
||||
r.RemoteAddr = "192.0.2.1:4242"
|
||||
if req.URL.Scheme == "https" {
|
||||
r.TLS = &tls.ConnectionState{}
|
||||
}
|
||||
if r.Body == nil {
|
||||
r.Body = http.NoBody
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, r)
|
||||
res := rec.Result()
|
||||
res.Request = req
|
||||
return res, nil
|
||||
}
|
||||
|
||||
func (m *memNet) client() *http.Client { return &http.Client{Transport: m} }
|
||||
|
||||
// fakeIdP est un fournisseur OIDC minimal : découverte, autorisation (connexion
|
||||
// immédiate), jetons, JWKS et déconnexion.
|
||||
type fakeIdP struct {
|
||||
t *testing.T
|
||||
srv *memServer
|
||||
rsaKey *rsa.PrivateKey
|
||||
ecKey *ecdsa.PrivateKey
|
||||
alg string // RS256, ES256 ou HS256
|
||||
secret string
|
||||
groups []string
|
||||
|
||||
codes map[string]url.Values // code -> paramètres de la demande d'autorisation
|
||||
}
|
||||
|
||||
func newIdP(t *testing.T, alg string) *fakeIdP {
|
||||
rk, _ := rsa.GenerateKey(rand.Reader, 2048)
|
||||
ek, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||
p := &fakeIdP{t: t, rsaKey: rk, ecKey: ek, alg: alg, secret: "secret-client-assez-long", codes: map[string]url.Values{}}
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/.well-known/openid-configuration", func(w http.ResponseWriter, r *http.Request) {
|
||||
_ = json.NewEncoder(w).Encode(map[string]string{
|
||||
"issuer": p.srv.URL,
|
||||
"authorization_endpoint": p.srv.URL + "/authorize",
|
||||
"token_endpoint": p.srv.URL + "/token",
|
||||
"jwks_uri": p.srv.URL + "/jwks",
|
||||
"end_session_endpoint": p.srv.URL + "/logout",
|
||||
})
|
||||
})
|
||||
mux.HandleFunc("/jwks", func(w http.ResponseWriter, r *http.Request) {
|
||||
e := big.NewInt(int64(rk.E)).Bytes()
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"keys": []map[string]string{
|
||||
{"kty": "RSA", "kid": "r1", "use": "sig", "n": b64.EncodeToString(rk.N.Bytes()), "e": b64.EncodeToString(e)},
|
||||
{"kty": "EC", "kid": "e1", "crv": "P-256", "x": b64.EncodeToString(ek.X.FillBytes(make([]byte, 32))), "y": b64.EncodeToString(ek.Y.FillBytes(make([]byte, 32)))},
|
||||
}})
|
||||
})
|
||||
mux.HandleFunc("/authorize", func(w http.ResponseWriter, r *http.Request) {
|
||||
q := r.URL.Query()
|
||||
code := randomString(8)
|
||||
p.codes[code] = q
|
||||
http.Redirect(w, r, q.Get("redirect_uri")+"?code="+code+"&state="+url.QueryEscape(q.Get("state")), http.StatusFound)
|
||||
})
|
||||
mux.HandleFunc("/token", func(w http.ResponseWriter, r *http.Request) {
|
||||
_ = r.ParseForm()
|
||||
q, ok := p.codes[r.Form.Get("code")]
|
||||
delete(p.codes, r.Form.Get("code"))
|
||||
id, sec, _ := r.BasicAuth()
|
||||
ch := sha256.Sum256([]byte(r.Form.Get("code_verifier")))
|
||||
switch {
|
||||
case !ok, id != "excalicloud", sec != p.secret,
|
||||
r.Form.Get("redirect_uri") != q.Get("redirect_uri"),
|
||||
q.Get("code_challenge_method") != "S256", b64.EncodeToString(ch[:]) != q.Get("code_challenge"):
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
_, _ = w.Write([]byte(`{"error":"invalid_grant"}`))
|
||||
return
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(map[string]string{"id_token": p.idToken(q.Get("nonce")), "token_type": "Bearer"})
|
||||
})
|
||||
p.srv = testNet.serve("idp", mux)
|
||||
return p
|
||||
}
|
||||
|
||||
func (p *fakeIdP) idToken(nonce string) string {
|
||||
claims := map[string]any{
|
||||
"iss": p.srv.URL, "sub": "u-42", "aud": "excalicloud", "nonce": nonce,
|
||||
"exp": time.Now().Add(5 * time.Minute).Unix(), "iat": time.Now().Unix(),
|
||||
"preferred_username": "cedric", "email": "cedric@example.org",
|
||||
}
|
||||
if p.groups != nil {
|
||||
claims["groups"] = p.groups
|
||||
}
|
||||
return p.sign(claims)
|
||||
}
|
||||
|
||||
func (p *fakeIdP) sign(claims map[string]any) string {
|
||||
hdr := map[string]string{"alg": p.alg, "typ": "JWT"}
|
||||
switch p.alg {
|
||||
case "RS256":
|
||||
hdr["kid"] = "r1"
|
||||
case "ES256":
|
||||
hdr["kid"] = "e1"
|
||||
}
|
||||
hb, _ := json.Marshal(hdr)
|
||||
cb, _ := json.Marshal(claims)
|
||||
signed := b64.EncodeToString(hb) + "." + b64.EncodeToString(cb)
|
||||
d := sha256.Sum256([]byte(signed))
|
||||
var sig []byte
|
||||
switch p.alg {
|
||||
case "RS256":
|
||||
sig, _ = rsa.SignPKCS1v15(rand.Reader, p.rsaKey, crypto.SHA256, d[:])
|
||||
case "ES256":
|
||||
r, s, _ := ecdsa.Sign(rand.Reader, p.ecKey, d[:])
|
||||
sig = append(r.FillBytes(make([]byte, 32)), s.FillBytes(make([]byte, 32))...)
|
||||
case "HS256":
|
||||
m := hmac.New(sha256.New, []byte(p.secret))
|
||||
m.Write([]byte(signed))
|
||||
sig = m.Sum(nil)
|
||||
}
|
||||
return signed + "." + b64.EncodeToString(sig)
|
||||
}
|
||||
|
||||
// app démarre excalicloud (routes /auth/*, une API et une page protégées, un
|
||||
// chemin public) avec l'authentification OIDC.
|
||||
func app(t *testing.T, idp *fakeIdP, groups []string) (*memServer, *http.Client) {
|
||||
t.Helper()
|
||||
mux := http.NewServeMux()
|
||||
var srv *memServer
|
||||
o, err := NewOIDC(context.Background(), Config{
|
||||
Issuer: idp.srv.URL, ClientID: "excalicloud", ClientSecret: idp.secret,
|
||||
AllowedGroups: groups, EndSession: true, Secret: []byte("0123456789abcdef0123456789abcdef"),
|
||||
Client: testNet.client(),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
o.Register(mux)
|
||||
mux.HandleFunc("GET /api/me", func(w http.ResponseWriter, r *http.Request) {
|
||||
_ = json.NewEncoder(w).Encode(UserFrom(r.Context()))
|
||||
})
|
||||
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte("app")) })
|
||||
srv = testNet.serve("app", o.Middleware(mux, func(p string) bool { return strings.HasPrefix(p, "/s/") }))
|
||||
jar, _ := cookiejar.New(nil)
|
||||
return srv, &http.Client{Jar: jar, Transport: testNet}
|
||||
}
|
||||
|
||||
func get(t *testing.T, c *http.Client, u string) (*http.Response, string) {
|
||||
t.Helper()
|
||||
res, err := c.Get(u)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer res.Body.Close()
|
||||
b, _ := io.ReadAll(res.Body)
|
||||
return res, string(b)
|
||||
}
|
||||
|
||||
func TestLoginFlow(t *testing.T) {
|
||||
for _, alg := range []string{"RS256", "ES256", "HS256"} {
|
||||
t.Run(alg, func(t *testing.T) {
|
||||
idp := newIdP(t, alg)
|
||||
srv, c := app(t, idp, nil)
|
||||
|
||||
// Sans session : 401 avec l'adresse de connexion pour l'API...
|
||||
res, _ := get(t, c, srv.URL+"/api/me")
|
||||
if res.StatusCode != 401 || res.Header.Get(LoginHeader) != "/auth/login" {
|
||||
t.Fatalf("API sans session : %d %q", res.StatusCode, res.Header.Get(LoginHeader))
|
||||
}
|
||||
// ... page de redirection (fragment conservé) pour la navigation.
|
||||
res, body := get(t, c, srv.URL+"/")
|
||||
if res.StatusCode != 401 || !strings.Contains(body, "location.hash") {
|
||||
t.Fatalf("navigation sans session : %d", res.StatusCode)
|
||||
}
|
||||
// Chemin public accessible.
|
||||
if res, _ := get(t, c, srv.URL+"/s/x.y"); res.StatusCode != 200 {
|
||||
t.Fatalf("chemin public : %d", res.StatusCode)
|
||||
}
|
||||
|
||||
// Connexion complète : login -> fournisseur -> callback -> next.
|
||||
res, body = get(t, c, srv.URL+"/auth/login?next="+url.QueryEscape("/dossier?x=1"))
|
||||
if res.StatusCode != 200 || body != "app" || res.Request.URL.RequestURI() != "/dossier?x=1" {
|
||||
t.Fatalf("après connexion : %d %q %s", res.StatusCode, body, res.Request.URL)
|
||||
}
|
||||
res, body = get(t, c, srv.URL+"/api/me")
|
||||
if res.StatusCode != 200 || !strings.Contains(body, `"name":"cedric"`) || !strings.Contains(body, `"sub":"u-42"`) {
|
||||
t.Fatalf("/api/me : %d %s", res.StatusCode, body)
|
||||
}
|
||||
|
||||
// Déconnexion : cookie effacé, renvoi vers end_session_endpoint.
|
||||
nc := &http.Client{Jar: c.Jar, Transport: testNet, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
|
||||
res, _ = get(t, nc, srv.URL+"/auth/logout")
|
||||
loc, _ := url.Parse(res.Header.Get("Location"))
|
||||
if res.StatusCode != 302 || loc.Path != "/logout" || loc.Query().Get("client_id") != "excalicloud" ||
|
||||
loc.Query().Get("post_logout_redirect_uri") != srv.URL+"/auth/logged-out" {
|
||||
t.Fatalf("logout : %d %s", res.StatusCode, loc)
|
||||
}
|
||||
if res, _ := get(t, c, srv.URL+"/api/me"); res.StatusCode != 401 {
|
||||
t.Fatalf("après déconnexion : %d", res.StatusCode)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAllowedGroups(t *testing.T) {
|
||||
idp := newIdP(t, "RS256")
|
||||
idp.groups = []string{"/excalicloud-users"} // chemin complet Keycloak
|
||||
srv, c := app(t, idp, []string{"excalicloud-users"})
|
||||
if res, body := get(t, c, srv.URL+"/auth/login"); res.StatusCode != 200 || body != "app" {
|
||||
t.Fatalf("membre du groupe : %d %q", res.StatusCode, body)
|
||||
}
|
||||
|
||||
idp2 := newIdP(t, "RS256")
|
||||
idp2.groups = []string{"autres"}
|
||||
srv2, c2 := app(t, idp2, []string{"excalicloud-users"})
|
||||
if res, _ := get(t, c2, srv2.URL+"/auth/login"); res.StatusCode != 403 {
|
||||
t.Fatalf("hors groupe : %d", res.StatusCode)
|
||||
}
|
||||
if res, _ := get(t, c2, srv2.URL+"/api/me"); res.StatusCode != 401 {
|
||||
t.Fatalf("hors groupe, pas de session attendue : %d", res.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCallbackRejectsForgedState(t *testing.T) {
|
||||
idp := newIdP(t, "RS256")
|
||||
srv, c := app(t, idp, nil)
|
||||
// Callback sans cookie d'état (CSRF de connexion) : refusé.
|
||||
if res, _ := get(t, c, srv.URL+"/auth/callback?code=x&state=y"); res.StatusCode != 400 {
|
||||
t.Fatalf("callback forgé : %d", res.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyIDToken(t *testing.T) {
|
||||
idp := newIdP(t, "RS256")
|
||||
o, err := NewOIDC(context.Background(), Config{Issuer: idp.srv.URL, ClientID: "excalicloud", Secret: []byte("0123456789abcdef"), Client: testNet.client()})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
d, err := o.provider(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
base := func() map[string]any {
|
||||
return map[string]any{"iss": idp.srv.URL, "sub": "s", "aud": []string{"excalicloud"}, "nonce": "n",
|
||||
"exp": time.Now().Add(time.Minute).Unix(), "iat": time.Now().Unix()}
|
||||
}
|
||||
if _, err := o.verifyIDToken(context.Background(), d, idp.sign(base()), "n"); err != nil {
|
||||
t.Fatalf("jeton valide refusé : %v", err)
|
||||
}
|
||||
bad := map[string]func(map[string]any){
|
||||
"émetteur": func(c map[string]any) { c["iss"] = "https://ailleurs" },
|
||||
"audience": func(c map[string]any) { c["aud"] = "autre" },
|
||||
"expiré": func(c map[string]any) { c["exp"] = time.Now().Add(-time.Hour).Unix() },
|
||||
"nonce": func(c map[string]any) { c["nonce"] = "x" },
|
||||
}
|
||||
for name, mutate := range bad {
|
||||
c := base()
|
||||
mutate(c)
|
||||
if _, err := o.verifyIDToken(context.Background(), d, idp.sign(c), "n"); err == nil {
|
||||
t.Errorf("%s : jeton accepté", name)
|
||||
}
|
||||
}
|
||||
// Signature altérée, alg none et HS256 sans secret client.
|
||||
tok := idp.sign(base())
|
||||
if _, err := o.verifyIDToken(context.Background(), d, tok[:len(tok)-4]+"AAAA", "n"); err == nil {
|
||||
t.Error("signature altérée acceptée")
|
||||
}
|
||||
parts := strings.Split(tok, ".")
|
||||
none := b64.EncodeToString([]byte(`{"alg":"none"}`)) + "." + parts[1] + "."
|
||||
if _, err := o.verifyIDToken(context.Background(), d, none, "n"); err == nil {
|
||||
t.Error("alg none accepté")
|
||||
}
|
||||
idp.alg = "HS256"
|
||||
if _, err := o.verifyIDToken(context.Background(), d, idp.sign(base()), "n"); err == nil {
|
||||
t.Error("HS256 accepté sans secret client")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSafeNext(t *testing.T) {
|
||||
for in, want := range map[string]string{
|
||||
"/a/b?c=1": "/a/b?c=1",
|
||||
"//evil.example": "/",
|
||||
"/\\evil.example": "/",
|
||||
"https://evil": "/",
|
||||
"/auth/logout": "/",
|
||||
"": "/",
|
||||
"/x\r\nSet-Cookie:a": "/",
|
||||
} {
|
||||
if got := safeNext(in); got != want {
|
||||
t.Errorf("safeNext(%q) = %q, attendu %q", in, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionCookieTampering(t *testing.T) {
|
||||
s := signer{[]byte("0123456789abcdef")}
|
||||
v, _ := s.encode(session{User: User{Sub: "a"}, Exp: time.Now().Add(time.Hour).Unix()})
|
||||
var out session
|
||||
if err := s.decode(v, &out); err != nil || out.Sub != "a" {
|
||||
t.Fatalf("décodage : %v", err)
|
||||
}
|
||||
p, sig, _ := strings.Cut(v, ".")
|
||||
forged := b64.EncodeToString([]byte(`{"sub":"admin","exp":9999999999}`)) + "." + sig
|
||||
if s.decode(forged, &out) == nil || s.decode(p+".x", &out) == nil {
|
||||
t.Fatal("cookie altéré accepté")
|
||||
}
|
||||
if (signer{[]byte("autre-cle-0123456")}).decode(v, &out) == nil {
|
||||
t.Fatal("cookie signé par une autre clé accepté")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadSecret(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
if _, err := LoadSecret("court", dir); err == nil {
|
||||
t.Fatal("secret trop court accepté")
|
||||
}
|
||||
k1, err := LoadSecret("", dir)
|
||||
if err != nil || len(k1) != 32 {
|
||||
t.Fatalf("génération : %v", err)
|
||||
}
|
||||
fi, _ := os.Stat(filepath.Join(dir, ".session-secret"))
|
||||
if fi.Mode().Perm() != 0o600 {
|
||||
t.Fatalf("droits %v", fi.Mode().Perm())
|
||||
}
|
||||
k2, _ := LoadSecret("", dir)
|
||||
if string(k1) != string(k2) {
|
||||
t.Fatal("clé non conservée entre deux démarrages")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"crypto"
|
||||
"crypto/ecdsa"
|
||||
"crypto/elliptic"
|
||||
"crypto/hmac"
|
||||
"crypto/rsa"
|
||||
_ "crypto/sha256" // enregistre SHA-256 pour crypto.Hash
|
||||
_ "crypto/sha512" // enregistre SHA-384 et SHA-512
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math/big"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// jwk est une clé publique d'un JWKS (RFC 7517), RSA ou EC.
|
||||
type jwk struct {
|
||||
Kty string `json:"kty"`
|
||||
Kid string `json:"kid"`
|
||||
Use string `json:"use"`
|
||||
Alg string `json:"alg"`
|
||||
N string `json:"n"`
|
||||
E string `json:"e"`
|
||||
Crv string `json:"crv"`
|
||||
X string `json:"x"`
|
||||
Y string `json:"y"`
|
||||
}
|
||||
|
||||
func (k jwk) publicKey() (crypto.PublicKey, error) {
|
||||
switch k.Kty {
|
||||
case "RSA":
|
||||
n, err1 := b64.DecodeString(k.N)
|
||||
e, err2 := b64.DecodeString(k.E)
|
||||
if err1 != nil || err2 != nil || len(n) == 0 || len(e) == 0 || len(e) > 4 {
|
||||
return nil, errors.New("clé RSA invalide")
|
||||
}
|
||||
return &rsa.PublicKey{N: new(big.Int).SetBytes(n), E: int(new(big.Int).SetBytes(e).Int64())}, nil
|
||||
case "EC":
|
||||
var c elliptic.Curve
|
||||
switch k.Crv {
|
||||
case "P-256":
|
||||
c = elliptic.P256()
|
||||
case "P-384":
|
||||
c = elliptic.P384()
|
||||
case "P-521":
|
||||
c = elliptic.P521()
|
||||
default:
|
||||
return nil, fmt.Errorf("courbe %q non prise en charge", k.Crv)
|
||||
}
|
||||
x, err1 := b64.DecodeString(k.X)
|
||||
y, err2 := b64.DecodeString(k.Y)
|
||||
if err1 != nil || err2 != nil {
|
||||
return nil, errors.New("clé EC invalide")
|
||||
}
|
||||
pub := &ecdsa.PublicKey{Curve: c, X: new(big.Int).SetBytes(x), Y: new(big.Int).SetBytes(y)}
|
||||
if !c.IsOnCurve(pub.X, pub.Y) {
|
||||
return nil, errors.New("clé EC invalide")
|
||||
}
|
||||
return pub, nil
|
||||
}
|
||||
return nil, fmt.Errorf("type de clé %q non pris en charge", k.Kty)
|
||||
}
|
||||
|
||||
var algHash = map[string]crypto.Hash{
|
||||
"RS256": crypto.SHA256, "RS384": crypto.SHA384, "RS512": crypto.SHA512,
|
||||
"PS256": crypto.SHA256, "PS384": crypto.SHA384, "PS512": crypto.SHA512,
|
||||
"ES256": crypto.SHA256, "ES384": crypto.SHA384, "ES512": crypto.SHA512,
|
||||
"HS256": crypto.SHA256, "HS384": crypto.SHA384, "HS512": crypto.SHA512,
|
||||
}
|
||||
|
||||
type jwtHeader struct {
|
||||
Alg string `json:"alg"`
|
||||
Kid string `json:"kid"`
|
||||
}
|
||||
|
||||
// parseJWT découpe un JWS compact et renvoie l'en-tête, les claims bruts, le
|
||||
// contenu signé et la signature.
|
||||
func parseJWT(token string) (h jwtHeader, claims []byte, signed string, sig []byte, err error) {
|
||||
parts := strings.Split(token, ".")
|
||||
if len(parts) != 3 {
|
||||
return h, nil, "", nil, errors.New("jeton mal formé")
|
||||
}
|
||||
hb, err := b64.DecodeString(parts[0])
|
||||
if err != nil || json.Unmarshal(hb, &h) != nil {
|
||||
return h, nil, "", nil, errors.New("en-tête de jeton invalide")
|
||||
}
|
||||
if claims, err = b64.DecodeString(parts[1]); err != nil {
|
||||
return h, nil, "", nil, errors.New("contenu de jeton invalide")
|
||||
}
|
||||
if sig, err = b64.DecodeString(parts[2]); err != nil {
|
||||
return h, nil, "", nil, errors.New("signature de jeton invalide")
|
||||
}
|
||||
return h, claims, parts[0] + "." + parts[1], sig, nil
|
||||
}
|
||||
|
||||
// verifySignature vérifie la signature avec une clé publique (RS, PS, ES) ou
|
||||
// le secret client (HS, clé symétrique utilisée par exemple par Authentik
|
||||
// quand aucun certificat de signature n'est choisi).
|
||||
func verifySignature(alg string, key crypto.PublicKey, secret []byte, signed string, sig []byte) error {
|
||||
hash, ok := algHash[alg]
|
||||
if !ok {
|
||||
return fmt.Errorf("algorithme %q refusé", alg)
|
||||
}
|
||||
if strings.HasPrefix(alg, "HS") {
|
||||
if len(secret) == 0 {
|
||||
return fmt.Errorf("jeton %s sans OIDC_CLIENT_SECRET", alg)
|
||||
}
|
||||
m := hmac.New(hash.New, secret)
|
||||
m.Write([]byte(signed))
|
||||
if !hmac.Equal(m.Sum(nil), sig) {
|
||||
return errors.New("signature invalide")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
d := hash.New()
|
||||
d.Write([]byte(signed))
|
||||
digest := d.Sum(nil)
|
||||
switch k := key.(type) {
|
||||
case *rsa.PublicKey:
|
||||
var err error
|
||||
switch alg[:2] {
|
||||
case "RS":
|
||||
err = rsa.VerifyPKCS1v15(k, hash, digest, sig)
|
||||
case "PS":
|
||||
err = rsa.VerifyPSS(k, hash, digest, sig, &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash})
|
||||
default:
|
||||
err = errors.New("algorithme incompatible avec une clé RSA")
|
||||
}
|
||||
if err != nil {
|
||||
return errors.New("signature invalide")
|
||||
}
|
||||
return nil
|
||||
case *ecdsa.PublicKey:
|
||||
size := (k.Curve.Params().BitSize + 7) / 8
|
||||
if alg[:2] != "ES" || len(sig) != 2*size {
|
||||
return errors.New("signature invalide")
|
||||
}
|
||||
r, s := new(big.Int).SetBytes(sig[:size]), new(big.Int).SetBytes(sig[size:])
|
||||
if !ecdsa.Verify(k, digest, r, s) {
|
||||
return errors.New("signature invalide")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return errors.New("clé de vérification inadaptée")
|
||||
}
|
||||
|
||||
// idClaims regroupe les claims utiles d'un ID Token.
|
||||
type idClaims struct {
|
||||
Iss string `json:"iss"`
|
||||
Sub string `json:"sub"`
|
||||
Aud json.RawMessage `json:"aud"`
|
||||
Azp string `json:"azp"`
|
||||
Exp json.Number `json:"exp"`
|
||||
Iat json.Number `json:"iat"`
|
||||
Nonce string `json:"nonce"`
|
||||
Name string `json:"name"`
|
||||
PreferredUsername string `json:"preferred_username"`
|
||||
Email string `json:"email"`
|
||||
}
|
||||
|
||||
func (c idClaims) audiences() []string {
|
||||
var one string
|
||||
if json.Unmarshal(c.Aud, &one) == nil {
|
||||
return []string{one}
|
||||
}
|
||||
var many []string
|
||||
_ = json.Unmarshal(c.Aud, &many)
|
||||
return many
|
||||
}
|
||||
|
||||
const clockSkew = 2 * time.Minute
|
||||
|
||||
// validate contrôle émetteur, audience, dates et nonce (OIDC Core 3.1.3.7).
|
||||
func (c idClaims) validate(issuer, clientID, nonce string, t time.Time) error {
|
||||
if c.Iss != issuer {
|
||||
return fmt.Errorf("émetteur %q inattendu", c.Iss)
|
||||
}
|
||||
if c.Sub == "" {
|
||||
return errors.New("claim sub absent")
|
||||
}
|
||||
aud := c.audiences()
|
||||
found := false
|
||||
for _, a := range aud {
|
||||
found = found || a == clientID
|
||||
}
|
||||
if !found {
|
||||
return errors.New("jeton destiné à un autre client")
|
||||
}
|
||||
if len(aud) > 1 && c.Azp != "" && c.Azp != clientID {
|
||||
return errors.New("azp inattendu")
|
||||
}
|
||||
exp, err := c.Exp.Int64()
|
||||
if err != nil {
|
||||
f, ferr := c.Exp.Float64()
|
||||
if ferr != nil {
|
||||
return errors.New("claim exp invalide")
|
||||
}
|
||||
exp = int64(f)
|
||||
}
|
||||
if t.After(time.Unix(exp, 0).Add(clockSkew)) {
|
||||
return errors.New("jeton expiré")
|
||||
}
|
||||
if iat, err := c.Iat.Float64(); err == nil && time.Unix(int64(iat), 0).After(t.Add(clockSkew)) {
|
||||
return errors.New("jeton émis dans le futur (horloge ?)")
|
||||
}
|
||||
if !hmac.Equal([]byte(c.Nonce), []byte(nonce)) {
|
||||
return errors.New("nonce invalide")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// stringList lit un claim chaîne ou tableau de chaînes (groupes, rôles).
|
||||
func stringList(v any) []string {
|
||||
switch x := v.(type) {
|
||||
case string:
|
||||
return []string{x}
|
||||
case []any:
|
||||
out := make([]string, 0, len(x))
|
||||
for _, e := range x {
|
||||
if s, ok := e.(string); ok {
|
||||
out = append(out, s)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// claimPath lit un claim éventuellement imbriqué (« realm_access.roles »).
|
||||
func claimPath(all map[string]any, p string) any {
|
||||
var cur any = all
|
||||
for _, part := range strings.Split(p, ".") {
|
||||
m, ok := cur.(map[string]any)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
cur = m[part]
|
||||
}
|
||||
return cur
|
||||
}
|
||||
@@ -0,0 +1,571 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto"
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"html"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
sessionCookie = "upandown_session"
|
||||
stateCookie = "upandown_oidc"
|
||||
stateTTL = 10 * time.Minute
|
||||
|
||||
// LoginHeader accompagne les réponses 401 de l'API : le frontend y lit
|
||||
// l'adresse de connexion.
|
||||
LoginHeader = "X-Auth-Login"
|
||||
)
|
||||
|
||||
// Config regroupe les réglages OIDC (variables OIDC_* et SESSION_*).
|
||||
type Config struct {
|
||||
Issuer string // OIDC_ISSUER
|
||||
ClientID string // OIDC_CLIENT_ID
|
||||
ClientSecret string // OIDC_CLIENT_SECRET (vide : client public, PKCE seul)
|
||||
RedirectURL string // OIDC_REDIRECT_URL (vide : https://<hôte>/auth/callback)
|
||||
Scopes []string // OIDC_SCOPES
|
||||
// AllowedGroups restreint l'accès aux membres d'au moins un de ces groupes
|
||||
// (claim GroupsClaim) ; vide : tout utilisateur authentifié.
|
||||
AllowedGroups []string
|
||||
GroupsClaim string // OIDC_GROUPS_CLAIM, « groups » par défaut
|
||||
EndSession bool // OIDC_LOGOUT : déconnexion aussi chez le fournisseur
|
||||
SessionTTL time.Duration
|
||||
Secret []byte // clé HMAC des cookies
|
||||
Client *http.Client
|
||||
// Sessions : gestionnaire de sessions partagé avec l'authentification locale
|
||||
// (nil : créé à partir de Secret et SessionTTL).
|
||||
Sessions *Sessions
|
||||
// Provision est appelé après une connexion réussie, avant l'ouverture de la
|
||||
// session : il crée ou met à jour le compte et peut refuser la connexion
|
||||
// (ErrPending, ErrDisabled). Il renvoie l'utilisateur de la session.
|
||||
Provision func(u User, groups []string) (User, error)
|
||||
}
|
||||
|
||||
// discovery est la partie utile de /.well-known/openid-configuration.
|
||||
type discovery struct {
|
||||
Issuer string `json:"issuer"`
|
||||
AuthorizationEndpoint string `json:"authorization_endpoint"`
|
||||
TokenEndpoint string `json:"token_endpoint"`
|
||||
JWKSURI string `json:"jwks_uri"`
|
||||
EndSessionEndpoint string `json:"end_session_endpoint"`
|
||||
}
|
||||
|
||||
// OIDC authentifie les utilisateurs auprès d'un fournisseur OpenID Connect
|
||||
// (Authentik, Keycloak, Entra ID, Google, Dex...).
|
||||
type OIDC struct {
|
||||
cfg Config
|
||||
signer signer
|
||||
sess *Sessions
|
||||
|
||||
mu sync.Mutex
|
||||
disc *discovery // nil : pas encore découvert
|
||||
keys map[string]crypto.PublicKey
|
||||
keysAt time.Time
|
||||
discErr time.Time // dernier échec de découverte (limite les tentatives)
|
||||
}
|
||||
|
||||
// NewOIDC prépare l'authentification ; la découverte du fournisseur est
|
||||
// tentée tout de suite puis, en cas d'échec, à la première connexion.
|
||||
func NewOIDC(ctx context.Context, cfg Config) (*OIDC, error) {
|
||||
if cfg.Issuer == "" || cfg.ClientID == "" {
|
||||
return nil, errors.New("OIDC_ISSUER et OIDC_CLIENT_ID sont requis en mode oidc")
|
||||
}
|
||||
if len(cfg.Secret) < 16 {
|
||||
return nil, errors.New("clé de session trop courte")
|
||||
}
|
||||
if cfg.RedirectURL != "" {
|
||||
u, err := url.Parse(cfg.RedirectURL)
|
||||
if err != nil || (u.Scheme != "https" && u.Scheme != "http") || u.Host == "" {
|
||||
return nil, errors.New("OIDC_REDIRECT_URL invalide (URL absolue attendue)")
|
||||
}
|
||||
}
|
||||
if len(cfg.Scopes) == 0 {
|
||||
cfg.Scopes = []string{"openid", "profile", "email"}
|
||||
}
|
||||
if !slices.Contains(cfg.Scopes, "openid") {
|
||||
cfg.Scopes = append([]string{"openid"}, cfg.Scopes...)
|
||||
}
|
||||
if cfg.GroupsClaim == "" {
|
||||
cfg.GroupsClaim = "groups"
|
||||
}
|
||||
if cfg.SessionTTL <= 0 {
|
||||
cfg.SessionTTL = 24 * time.Hour
|
||||
}
|
||||
if cfg.Client == nil {
|
||||
cfg.Client = &http.Client{Timeout: 15 * time.Second}
|
||||
}
|
||||
if cfg.Sessions == nil {
|
||||
cfg.Sessions = NewSessions(cfg.Secret, cfg.SessionTTL, strings.HasPrefix(cfg.RedirectURL, "https://"))
|
||||
}
|
||||
a := &OIDC{cfg: cfg, signer: signer{cfg.Secret}, sess: cfg.Sessions}
|
||||
if _, err := a.provider(ctx); err != nil {
|
||||
slog.Warn("fournisseur OIDC injoignable, nouvel essai à la première connexion", "issuer", cfg.Issuer, "err", err)
|
||||
}
|
||||
return a, nil
|
||||
}
|
||||
|
||||
func (a *OIDC) getJSON(ctx context.Context, u string, v any) error {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set("Accept", "application/json")
|
||||
res, err := a.cfg.Client.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer res.Body.Close()
|
||||
if res.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("%s : HTTP %d", u, res.StatusCode)
|
||||
}
|
||||
return json.NewDecoder(io.LimitReader(res.Body, 1<<20)).Decode(v)
|
||||
}
|
||||
|
||||
// provider renvoie la configuration découverte (mise en cache).
|
||||
func (a *OIDC) provider(ctx context.Context) (*discovery, error) {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if a.disc != nil {
|
||||
return a.disc, nil
|
||||
}
|
||||
if time.Since(a.discErr) < 5*time.Second {
|
||||
return nil, errors.New("fournisseur OIDC injoignable")
|
||||
}
|
||||
var d discovery
|
||||
u := strings.TrimRight(a.cfg.Issuer, "/") + "/.well-known/openid-configuration"
|
||||
if err := a.getJSON(ctx, u, &d); err != nil {
|
||||
a.discErr = time.Now()
|
||||
return nil, err
|
||||
}
|
||||
if strings.TrimRight(d.Issuer, "/") != strings.TrimRight(a.cfg.Issuer, "/") {
|
||||
a.discErr = time.Now()
|
||||
return nil, fmt.Errorf("l'émetteur annoncé (%s) ne correspond pas à OIDC_ISSUER", d.Issuer)
|
||||
}
|
||||
if d.AuthorizationEndpoint == "" || d.TokenEndpoint == "" || d.JWKSURI == "" {
|
||||
a.discErr = time.Now()
|
||||
return nil, errors.New("configuration OIDC incomplète (authorization, token ou jwks absent)")
|
||||
}
|
||||
a.disc = &d
|
||||
slog.Info("fournisseur OIDC découvert", "issuer", d.Issuer)
|
||||
return a.disc, nil
|
||||
}
|
||||
|
||||
// key renvoie la clé publique kid, en rechargeant le JWKS si elle est
|
||||
// inconnue (rotation de clés), au plus une fois par minute.
|
||||
func (a *OIDC) key(ctx context.Context, d *discovery, kid, alg string) (crypto.PublicKey, error) {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
find := func() crypto.PublicKey {
|
||||
if k, ok := a.keys[kid]; ok {
|
||||
return k
|
||||
}
|
||||
if kid == "" && len(a.keys) == 1 {
|
||||
for _, k := range a.keys {
|
||||
return k
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if k := find(); k != nil {
|
||||
return k, nil
|
||||
}
|
||||
if time.Since(a.keysAt) < time.Minute && a.keys != nil {
|
||||
return nil, fmt.Errorf("clé %q inconnue", kid)
|
||||
}
|
||||
var set struct {
|
||||
Keys []jwk `json:"keys"`
|
||||
}
|
||||
if err := a.getJSON(ctx, d.JWKSURI, &set); err != nil {
|
||||
return nil, fmt.Errorf("JWKS : %w", err)
|
||||
}
|
||||
a.keys = map[string]crypto.PublicKey{}
|
||||
a.keysAt = time.Now()
|
||||
for _, j := range set.Keys {
|
||||
if j.Use != "" && j.Use != "sig" {
|
||||
continue
|
||||
}
|
||||
if pk, err := j.publicKey(); err == nil {
|
||||
a.keys[j.Kid] = pk
|
||||
}
|
||||
}
|
||||
if k := find(); k != nil {
|
||||
return k, nil
|
||||
}
|
||||
return nil, fmt.Errorf("clé %q absente du JWKS (alg %s)", kid, alg)
|
||||
}
|
||||
|
||||
// --- Routes /auth/* -----------------------------------------------------------
|
||||
|
||||
// Register ajoute /auth/login, /auth/callback, /auth/logout et /auth/logged-out.
|
||||
func (a *OIDC) Register(mux *http.ServeMux) {
|
||||
a.RegisterLogin(mux)
|
||||
mux.HandleFunc("GET /auth/logout", a.logout)
|
||||
mux.HandleFunc("POST /auth/logout", a.logout)
|
||||
}
|
||||
|
||||
// RegisterLogin ajoute /auth/login, /auth/callback et /auth/logged-out (la
|
||||
// déconnexion est alors portée par l'appelant, voir Auth).
|
||||
func (a *OIDC) RegisterLogin(mux *http.ServeMux) {
|
||||
mux.HandleFunc("GET /auth/login", a.login)
|
||||
mux.HandleFunc("GET /auth/callback", a.callback)
|
||||
mux.HandleFunc("GET /auth/logged-out", func(w http.ResponseWriter, r *http.Request) {
|
||||
page(w, http.StatusOK, "Déconnecté", "Vous êtes déconnecté.", "/", "Se reconnecter")
|
||||
})
|
||||
}
|
||||
|
||||
func secure(r *http.Request) bool {
|
||||
return r.TLS != nil || strings.EqualFold(r.Header.Get("X-Forwarded-Proto"), "https")
|
||||
}
|
||||
|
||||
// baseURL est l'origine publique du service : celle de OIDC_REDIRECT_URL si
|
||||
// elle est fixée, sinon celle de la requête (en-têtes X-Forwarded-* compris).
|
||||
func (a *OIDC) baseURL(r *http.Request) string {
|
||||
if a.cfg.RedirectURL != "" {
|
||||
u, _ := url.Parse(a.cfg.RedirectURL)
|
||||
return u.Scheme + "://" + u.Host
|
||||
}
|
||||
scheme := "http"
|
||||
if secure(r) {
|
||||
scheme = "https"
|
||||
}
|
||||
host := r.Host
|
||||
if h := r.Header.Get("X-Forwarded-Host"); h != "" {
|
||||
host, _, _ = strings.Cut(h, ",")
|
||||
host = strings.TrimSpace(host)
|
||||
}
|
||||
return scheme + "://" + host
|
||||
}
|
||||
|
||||
func (a *OIDC) redirectURL(r *http.Request) string {
|
||||
if a.cfg.RedirectURL != "" {
|
||||
return a.cfg.RedirectURL
|
||||
}
|
||||
return a.baseURL(r) + "/auth/callback"
|
||||
}
|
||||
|
||||
func (a *OIDC) setCookie(w http.ResponseWriter, r *http.Request, name, value, path string, ttl time.Duration) {
|
||||
c := &http.Cookie{
|
||||
Name: name,
|
||||
Value: value,
|
||||
Path: path,
|
||||
HttpOnly: true,
|
||||
Secure: secure(r) || strings.HasPrefix(a.cfg.RedirectURL, "https://"),
|
||||
SameSite: http.SameSiteLaxMode, // envoyé au retour du fournisseur (navigation GET)
|
||||
}
|
||||
if ttl < 0 {
|
||||
c.MaxAge = -1
|
||||
} else {
|
||||
c.Expires = now().Add(ttl)
|
||||
c.MaxAge = int(ttl / time.Second)
|
||||
}
|
||||
http.SetCookie(w, c)
|
||||
}
|
||||
|
||||
// safeNext n'accepte que les chemins locaux (pas de redirection ouverte).
|
||||
func safeNext(next string) string {
|
||||
if !strings.HasPrefix(next, "/") || strings.HasPrefix(next, "//") || strings.HasPrefix(next, "/\\") ||
|
||||
strings.HasPrefix(next, "/auth/") || strings.ContainsAny(next, "\r\n") {
|
||||
return "/"
|
||||
}
|
||||
return next
|
||||
}
|
||||
|
||||
func (a *OIDC) login(w http.ResponseWriter, r *http.Request) {
|
||||
d, err := a.provider(r.Context())
|
||||
if err != nil {
|
||||
slog.Error("OIDC : découverte", "err", err)
|
||||
page(w, http.StatusBadGateway, "Connexion impossible",
|
||||
"Le fournisseur d'identité est injoignable pour l'instant.", r.URL.RequestURI(), "Réessayer")
|
||||
return
|
||||
}
|
||||
st := loginState{
|
||||
State: randomString(24),
|
||||
Nonce: randomString(24),
|
||||
Verifier: randomString(48), // 64 caractères (RFC 7636 : 43 à 128)
|
||||
Next: safeNext(r.URL.Query().Get("next")),
|
||||
Exp: now().Add(stateTTL).Unix(),
|
||||
}
|
||||
v, err := a.signer.encode(st)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
a.setCookie(w, r, stateCookie, v, "/auth/", stateTTL)
|
||||
|
||||
challenge := sha256.Sum256([]byte(st.Verifier))
|
||||
q := url.Values{
|
||||
"response_type": {"code"},
|
||||
"client_id": {a.cfg.ClientID},
|
||||
"redirect_uri": {a.redirectURL(r)},
|
||||
"scope": {strings.Join(a.cfg.Scopes, " ")},
|
||||
"state": {st.State},
|
||||
"nonce": {st.Nonce},
|
||||
"code_challenge": {b64.EncodeToString(challenge[:])},
|
||||
"code_challenge_method": {"S256"},
|
||||
}
|
||||
sep := "?"
|
||||
if strings.Contains(d.AuthorizationEndpoint, "?") {
|
||||
sep = "&"
|
||||
}
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
http.Redirect(w, r, d.AuthorizationEndpoint+sep+q.Encode(), http.StatusFound)
|
||||
}
|
||||
|
||||
func (a *OIDC) callback(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
q := r.URL.Query()
|
||||
retry := "/auth/login"
|
||||
var st loginState
|
||||
c, err := r.Cookie(stateCookie)
|
||||
if err == nil {
|
||||
err = a.signer.decode(c.Value, &st)
|
||||
}
|
||||
if err == nil && st.Next != "/" {
|
||||
retry += "?next=" + url.QueryEscape(st.Next)
|
||||
}
|
||||
a.setCookie(w, r, stateCookie, "", "/auth/", -1) // usage unique
|
||||
if e := q.Get("error"); e != "" {
|
||||
slog.Warn("OIDC : refus du fournisseur", "error", e, "description", q.Get("error_description"))
|
||||
page(w, http.StatusForbidden, "Connexion refusée", "Le fournisseur d'identité a refusé la connexion ("+e+").", retry, "Réessayer")
|
||||
return
|
||||
}
|
||||
if err != nil || st.Exp < now().Unix() || st.State == "" || q.Get("state") != st.State {
|
||||
page(w, http.StatusBadRequest, "Connexion expirée",
|
||||
"La demande de connexion est expirée ou invalide (cookies bloqués ?).", retry, "Recommencer")
|
||||
return
|
||||
}
|
||||
user, err := a.exchange(r, q.Get("code"), st)
|
||||
if errors.Is(err, errForbidden) {
|
||||
slog.Warn("OIDC : accès refusé", "sub", user.Sub, "name", user.Name)
|
||||
page(w, http.StatusForbidden, "Accès refusé",
|
||||
"Votre compte ("+user.Name+") n'appartient à aucun groupe autorisé.", "/auth/logout", "Changer de compte")
|
||||
return
|
||||
}
|
||||
if errors.Is(err, ErrPending) {
|
||||
page(w, http.StatusForbidden, "Compte en attente", "Votre compte ("+user.Name+") doit être validé par un administrateur.", "/auth/logout", "Changer de compte")
|
||||
return
|
||||
}
|
||||
if errors.Is(err, ErrDisabled) {
|
||||
page(w, http.StatusForbidden, "Compte désactivé", "Votre compte ("+user.Name+") a été désactivé.", "/auth/logout", "Changer de compte")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
slog.Error("OIDC : échange du code", "err", err)
|
||||
page(w, http.StatusBadGateway, "Connexion impossible", "La vérification de l'identité a échoué.", retry, "Réessayer")
|
||||
return
|
||||
}
|
||||
if err := a.startSession(w, r, user); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
slog.Info("connexion OIDC", "sub", user.Sub, "name", user.Name)
|
||||
http.Redirect(w, r, st.Next, http.StatusFound)
|
||||
}
|
||||
|
||||
var errForbidden = errors.New("utilisateur hors des groupes autorisés")
|
||||
|
||||
// exchange échange le code contre les jetons, vérifie l'ID Token et en tire
|
||||
// l'utilisateur.
|
||||
func (a *OIDC) exchange(r *http.Request, code string, st loginState) (User, error) {
|
||||
ctx := r.Context()
|
||||
d, err := a.provider(ctx)
|
||||
if err != nil {
|
||||
return User{}, err
|
||||
}
|
||||
form := url.Values{
|
||||
"grant_type": {"authorization_code"},
|
||||
"code": {code},
|
||||
"redirect_uri": {a.redirectURL(r)},
|
||||
"code_verifier": {st.Verifier},
|
||||
"client_id": {a.cfg.ClientID},
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, d.TokenEndpoint, strings.NewReader(form.Encode()))
|
||||
if err != nil {
|
||||
return User{}, err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
req.Header.Set("Accept", "application/json")
|
||||
if a.cfg.ClientSecret != "" { // client_secret_basic (RFC 6749 2.3.1)
|
||||
req.SetBasicAuth(url.QueryEscape(a.cfg.ClientID), url.QueryEscape(a.cfg.ClientSecret))
|
||||
}
|
||||
res, err := a.cfg.Client.Do(req)
|
||||
if err != nil {
|
||||
return User{}, err
|
||||
}
|
||||
defer res.Body.Close()
|
||||
var tok struct {
|
||||
IDToken string `json:"id_token"`
|
||||
Error string `json:"error"`
|
||||
Desc string `json:"error_description"`
|
||||
}
|
||||
if err := json.NewDecoder(io.LimitReader(res.Body, 1<<20)).Decode(&tok); err != nil {
|
||||
return User{}, fmt.Errorf("réponse du token endpoint (HTTP %d) : %w", res.StatusCode, err)
|
||||
}
|
||||
if res.StatusCode != http.StatusOK || tok.IDToken == "" {
|
||||
return User{}, fmt.Errorf("token endpoint : HTTP %d %s %s", res.StatusCode, tok.Error, tok.Desc)
|
||||
}
|
||||
u, err := a.verifyIDToken(ctx, d, tok.IDToken, st.Nonce)
|
||||
if err != nil {
|
||||
return u, err
|
||||
}
|
||||
if a.cfg.Provision != nil {
|
||||
return a.cfg.Provision(u, u.Groups)
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
func (a *OIDC) verifyIDToken(ctx context.Context, d *discovery, raw, nonce string) (User, error) {
|
||||
h, body, signed, sig, err := parseJWT(raw)
|
||||
if err != nil {
|
||||
return User{}, err
|
||||
}
|
||||
var key crypto.PublicKey
|
||||
if !strings.HasPrefix(h.Alg, "HS") {
|
||||
if key, err = a.key(ctx, d, h.Kid, h.Alg); err != nil {
|
||||
return User{}, err
|
||||
}
|
||||
}
|
||||
if err := verifySignature(h.Alg, key, []byte(a.cfg.ClientSecret), signed, sig); err != nil {
|
||||
return User{}, err
|
||||
}
|
||||
var c idClaims
|
||||
if err := json.Unmarshal(body, &c); err != nil {
|
||||
return User{}, errors.New("claims illisibles")
|
||||
}
|
||||
if err := c.validate(d.Issuer, a.cfg.ClientID, nonce, now()); err != nil {
|
||||
return User{}, err
|
||||
}
|
||||
u := User{Sub: c.Sub, Email: c.Email, Name: c.PreferredUsername}
|
||||
for _, n := range []string{c.Name, c.Email, c.Sub} {
|
||||
if u.Name == "" {
|
||||
u.Name = n
|
||||
}
|
||||
}
|
||||
var all map[string]any
|
||||
_ = json.Unmarshal(body, &all)
|
||||
groups := stringList(claimPath(all, a.cfg.GroupsClaim))
|
||||
for i, g := range groups {
|
||||
groups[i] = strings.TrimPrefix(g, "/") // Keycloak : chemin complet du groupe
|
||||
}
|
||||
u.Groups = groups
|
||||
if len(a.cfg.AllowedGroups) > 0 {
|
||||
ok := slices.ContainsFunc(groups, func(g string) bool {
|
||||
// Keycloak préfixe les groupes par « / » quand le chemin complet est inclus.
|
||||
return slices.Contains(a.cfg.AllowedGroups, g) || slices.Contains(a.cfg.AllowedGroups, strings.TrimPrefix(g, "/"))
|
||||
})
|
||||
if !ok {
|
||||
return u, errForbidden
|
||||
}
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
func (a *OIDC) startSession(w http.ResponseWriter, r *http.Request, u User) error {
|
||||
return a.sess.Start(w, r, u)
|
||||
}
|
||||
|
||||
func (a *OIDC) logout(w http.ResponseWriter, r *http.Request) {
|
||||
a.sess.Clear(w, r)
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
back := a.baseURL(r) + "/auth/logged-out"
|
||||
if a.cfg.EndSession {
|
||||
if d, err := a.provider(r.Context()); err == nil && d.EndSessionEndpoint != "" {
|
||||
// RP-Initiated Logout 1.0 : client_id identifie le client sans id_token_hint.
|
||||
q := url.Values{"client_id": {a.cfg.ClientID}, "post_logout_redirect_uri": {back}}
|
||||
sep := "?"
|
||||
if strings.Contains(d.EndSessionEndpoint, "?") {
|
||||
sep = "&"
|
||||
}
|
||||
http.Redirect(w, r, d.EndSessionEndpoint+sep+q.Encode(), http.StatusFound)
|
||||
return
|
||||
}
|
||||
}
|
||||
http.Redirect(w, r, back, http.StatusFound)
|
||||
}
|
||||
|
||||
// --- Protection des routes -------------------------------------------------------
|
||||
|
||||
type ctxKey struct{}
|
||||
|
||||
// UserFrom renvoie l'utilisateur de la requête (nil hors session OIDC).
|
||||
func UserFrom(ctx context.Context) *User {
|
||||
u, _ := ctx.Value(ctxKey{}).(*User)
|
||||
return u
|
||||
}
|
||||
|
||||
// WithUser renvoie ctx portant l'utilisateur u (authentification par jeton d'API).
|
||||
func WithUser(ctx context.Context, u *User) context.Context {
|
||||
return context.WithValue(ctx, ctxKey{}, u)
|
||||
}
|
||||
|
||||
// Session renvoie l'utilisateur du cookie de session s'il est valide.
|
||||
func (a *OIDC) session(r *http.Request) (session, bool) { return a.sess.Get(r) }
|
||||
|
||||
// Middleware exige une session sauf pour /auth/* et les chemins publics.
|
||||
// Navigation sans session : page qui renvoie vers /auth/login en conservant
|
||||
// l'URL complète (fragment #/dossier/schéma compris). API : 401 + LoginHeader.
|
||||
// La session est prolongée à chaque requête passée la moitié de sa durée.
|
||||
func (a *OIDC) Middleware(next http.Handler, public func(string) bool) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
p := r.URL.Path
|
||||
if strings.HasPrefix(p, "/auth/") || public(p) {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
s, ok := a.session(r)
|
||||
if !ok {
|
||||
if strings.HasPrefix(p, "/api/") || r.Method != http.MethodGet {
|
||||
w.Header().Set(LoginHeader, "/auth/login")
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
_, _ = w.Write([]byte(`{"error":"session expirée : reconnexion nécessaire"}`))
|
||||
return
|
||||
}
|
||||
loginRedirect(w)
|
||||
return
|
||||
}
|
||||
if time.Until(time.Unix(s.Exp, 0)) < a.cfg.SessionTTL/2 {
|
||||
_ = a.startSession(w, r, s.User)
|
||||
}
|
||||
u := s.User
|
||||
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), ctxKey{}, &u)))
|
||||
})
|
||||
}
|
||||
|
||||
// loginRedirect renvoie vers /auth/login par script pour conserver le
|
||||
// fragment de l'URL, que le navigateur n'envoie pas au serveur.
|
||||
func loginRedirect(w http.ResponseWriter) {
|
||||
h := w.Header()
|
||||
h.Set("Content-Type", "text/html; charset=utf-8")
|
||||
h.Set("Cache-Control", "no-store")
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
_, _ = io.WriteString(w, `<!doctype html><meta charset="utf-8"><title>Connexion</title>
|
||||
<script>location.replace("/auth/login?next="+encodeURIComponent(location.pathname+location.search+location.hash))</script>
|
||||
<noscript><a href="/auth/login">Se connecter</a></noscript>`)
|
||||
}
|
||||
|
||||
// page affiche un message simple (erreur de connexion, déconnexion).
|
||||
func page(w http.ResponseWriter, status int, title, msg, link, label string) {
|
||||
h := w.Header()
|
||||
h.Set("Content-Type", "text/html; charset=utf-8")
|
||||
h.Set("Cache-Control", "no-store")
|
||||
w.WriteHeader(status)
|
||||
e := html.EscapeString
|
||||
_, _ = fmt.Fprintf(w, `<!doctype html><html lang="fr"><meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1"><title>%s</title>
|
||||
<style>body{font:16px system-ui,sans-serif;display:grid;place-items:center;min-height:90vh;margin:0;color:#1b1b1f;background:#fff}
|
||||
@media(prefers-color-scheme:dark){body{color:#e3e3e8;background:#121212}}main{max-width:28rem;padding:1rem;text-align:center}
|
||||
a{display:inline-block;margin-top:1rem;padding:.6rem 1.2rem;border-radius:8px;background:#6965db;color:#fff;text-decoration:none}</style>
|
||||
<main><h1>%s</h1><p>%s</p><a href="%s">%s</a></main></html>`, e(title), e(title), e(msg), e(link), e(label))
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
// Package auth fournit l'authentification OpenID Connect (flux Authorization
|
||||
// Code + PKCE) et les sessions signées associées, sans dépendance externe.
|
||||
package auth
|
||||
|
||||
import (
|
||||
"crypto/hmac"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// User est l'utilisateur authentifié. Sub est l'identifiant du fournisseur
|
||||
// OIDC (vide pour un compte local) ; ID est celui du compte (nom de son
|
||||
// espace personnel) ; Role n'est jamais lu du cookie : il vient du compte.
|
||||
type User struct {
|
||||
ID string `json:"id,omitempty"`
|
||||
Sub string `json:"sub,omitempty"`
|
||||
Name string `json:"name"`
|
||||
Email string `json:"email,omitempty"`
|
||||
Provider string `json:"provider,omitempty"` // "local" ou "oidc"
|
||||
Role string `json:"role,omitempty"` // "admin" ou "user" (rempli par le middleware)
|
||||
Groups []string `json:"-"` // groupes OIDC de la connexion en cours
|
||||
}
|
||||
|
||||
// session est le contenu du cookie de session (signé, non chiffré : il ne
|
||||
// contient que l'identité, pas de jeton).
|
||||
type session struct {
|
||||
User
|
||||
Exp int64 `json:"exp"`
|
||||
}
|
||||
|
||||
// loginState accompagne l'aller-retour vers le fournisseur (cookie de 10 min).
|
||||
type loginState struct {
|
||||
State string `json:"state"`
|
||||
Nonce string `json:"nonce"`
|
||||
Verifier string `json:"verifier"`
|
||||
Next string `json:"next"`
|
||||
Exp int64 `json:"exp"`
|
||||
}
|
||||
|
||||
var errBadCookie = errors.New("cookie invalide")
|
||||
|
||||
// Erreurs de connexion.
|
||||
var (
|
||||
ErrBadCredentials = errors.New("identifiant ou mot de passe incorrect")
|
||||
ErrPending = errors.New("compte en attente de validation par un administrateur")
|
||||
ErrDisabled = errors.New("compte désactivé")
|
||||
)
|
||||
|
||||
// signer signe et vérifie des valeurs JSON (HMAC-SHA256).
|
||||
type signer struct{ key []byte }
|
||||
|
||||
var b64 = base64.RawURLEncoding
|
||||
|
||||
func (s signer) mac(payload string) string {
|
||||
m := hmac.New(sha256.New, s.key)
|
||||
m.Write([]byte(payload))
|
||||
return b64.EncodeToString(m.Sum(nil))
|
||||
}
|
||||
|
||||
func (s signer) encode(v any) (string, error) {
|
||||
raw, err := json.Marshal(v)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
p := b64.EncodeToString(raw)
|
||||
return p + "." + s.mac(p), nil
|
||||
}
|
||||
|
||||
// decode vérifie la signature puis décode ; le contrôle d'expiration revient
|
||||
// à l'appelant (champ Exp).
|
||||
func (s signer) decode(value string, v any) error {
|
||||
p, sig, ok := strings.Cut(value, ".")
|
||||
if !ok || !hmac.Equal([]byte(sig), []byte(s.mac(p))) {
|
||||
return errBadCookie
|
||||
}
|
||||
raw, err := b64.DecodeString(p)
|
||||
if err != nil {
|
||||
return errBadCookie
|
||||
}
|
||||
if json.Unmarshal(raw, v) != nil {
|
||||
return errBadCookie
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func randomString(n int) string {
|
||||
b := make([]byte, n)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
panic(err) // crypto/rand ne échoue pas sur les systèmes supportés
|
||||
}
|
||||
return b64.EncodeToString(b)
|
||||
}
|
||||
|
||||
// LoadSecret renvoie la clé de signature des sessions : secret si fourni
|
||||
// (16 caractères minimum), sinon le contenu de dir/.session-secret, créé
|
||||
// aléatoirement au premier démarrage (0600).
|
||||
func LoadSecret(secret, dir string) ([]byte, error) {
|
||||
if secret != "" {
|
||||
if len(secret) < 16 {
|
||||
return nil, errors.New("SESSION_SECRET trop court (16 caractères minimum)")
|
||||
}
|
||||
return []byte(secret), nil
|
||||
}
|
||||
file := filepath.Join(dir, ".session-secret")
|
||||
if b, err := os.ReadFile(file); err == nil {
|
||||
if k, err := hex.DecodeString(strings.TrimSpace(string(b))); err == nil && len(k) >= 32 {
|
||||
return k, nil
|
||||
}
|
||||
return nil, errors.New(file + " invalide (supprimer le fichier pour en générer un nouveau)")
|
||||
} else if !errors.Is(err, os.ErrNotExist) {
|
||||
return nil, err
|
||||
}
|
||||
k := make([]byte, 32)
|
||||
if _, err := rand.Read(k); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := os.WriteFile(file, []byte(hex.EncodeToString(k)+"\n"), 0o600); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return k, nil
|
||||
}
|
||||
|
||||
func now() time.Time { return time.Now() }
|
||||
|
||||
// Sessions gère le cookie de session signé, commun aux comptes locaux et OIDC.
|
||||
type Sessions struct {
|
||||
signer signer
|
||||
TTL time.Duration
|
||||
secure bool // cookie Secure même si la requête n'arrive pas en HTTPS (URL publique en https)
|
||||
}
|
||||
|
||||
// NewSessions crée un gestionnaire de sessions : secret signe les cookies, ttl
|
||||
// est la durée d'inactivité maximale.
|
||||
func NewSessions(secret []byte, ttl time.Duration, forceSecure bool) *Sessions {
|
||||
if ttl <= 0 {
|
||||
ttl = 24 * time.Hour
|
||||
}
|
||||
return &Sessions{signer: signer{secret}, TTL: ttl, secure: forceSecure}
|
||||
}
|
||||
|
||||
func (s *Sessions) cookie(w http.ResponseWriter, r *http.Request, value string, ttl time.Duration) {
|
||||
c := &http.Cookie{
|
||||
Name: sessionCookie,
|
||||
Value: value,
|
||||
Path: "/",
|
||||
HttpOnly: true,
|
||||
Secure: secure(r) || s.secure,
|
||||
SameSite: http.SameSiteLaxMode, // envoyé au retour du fournisseur (navigation GET)
|
||||
}
|
||||
if ttl < 0 {
|
||||
c.MaxAge = -1
|
||||
} else {
|
||||
c.Expires = now().Add(ttl)
|
||||
c.MaxAge = int(ttl / time.Second)
|
||||
}
|
||||
http.SetCookie(w, c)
|
||||
}
|
||||
|
||||
// Start ouvre (ou prolonge) la session de u.
|
||||
func (s *Sessions) Start(w http.ResponseWriter, r *http.Request, u User) error {
|
||||
v, err := s.signer.encode(session{User: u, Exp: now().Add(s.TTL).Unix()})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
s.cookie(w, r, v, s.TTL)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Clear supprime le cookie de session.
|
||||
func (s *Sessions) Clear(w http.ResponseWriter, r *http.Request) { s.cookie(w, r, "", -1) }
|
||||
|
||||
// Get renvoie la session du cookie s'il est valide.
|
||||
func (s *Sessions) Get(r *http.Request) (session, bool) {
|
||||
var v session
|
||||
c, err := r.Cookie(sessionCookie)
|
||||
if err != nil || s.signer.decode(c.Value, &v) != nil || v.Exp < now().Unix() || (v.Sub == "" && v.ID == "") {
|
||||
return v, false
|
||||
}
|
||||
return v, true
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"image"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Détails des fichiers et dossiers pour la vue Galerie et le panneau Détails
|
||||
// (/api/list?details=1) : dimensions d'une image, versions, liens de partage
|
||||
// actifs, création et dernier auteur ; contenu d'un dossier.
|
||||
|
||||
// Details complète une entrée.
|
||||
type Details struct {
|
||||
Width int `json:"width,omitempty"` // image : dimensions en pixels
|
||||
Height int `json:"height,omitempty"`
|
||||
|
||||
Versions int `json:"versions,omitempty"` // versions dans l'historique
|
||||
Shares int `json:"shares,omitempty"` // liens de partage actifs
|
||||
Created *time.Time `json:"created,omitempty"` // création (ou plus ancienne version connue)
|
||||
CreatedBy string `json:"createdBy,omitempty"` // vide si inconnu
|
||||
|
||||
Dirs int `json:"dirs,omitempty"` // dossier : sous-dossiers directs
|
||||
Files int `json:"files,omitempty"` // dossier : fichiers directs
|
||||
Total int64 `json:"total,omitempty"` // dossier : taille de tout le contenu (octets)
|
||||
Count int `json:"count,omitempty"` // dossier : nombre de fichiers dans tout le contenu
|
||||
}
|
||||
|
||||
// maxDirWalk borne le parcours qui totalise la taille d'un dossier.
|
||||
const maxDirWalk = 20000
|
||||
|
||||
func (s *Store) fileDetails(rel string, meta map[string]itemMeta, shares map[string]int) (*Details, error) {
|
||||
c, abs, err := s.resolve(rel)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
fi, err := os.Lstat(abs)
|
||||
if err != nil {
|
||||
return nil, mapErr(err)
|
||||
}
|
||||
d := &Details{Shares: shares[c]}
|
||||
if isDecodableImage(c) && fi.Size() < 200<<20 {
|
||||
if f, err := os.Open(abs); err == nil {
|
||||
if cfg, _, err := image.DecodeConfig(f); err == nil {
|
||||
d.Width, d.Height = cfg.Width, cfg.Height
|
||||
}
|
||||
f.Close()
|
||||
}
|
||||
}
|
||||
var oldest string
|
||||
d.Versions, oldest = s.versionCount(c)
|
||||
if m := meta[c]; m.Created != nil {
|
||||
d.Created, d.CreatedBy = m.Created, m.CreatedBy
|
||||
} else if t, err := time.Parse(versionLayout, oldest); err == nil {
|
||||
d.Created = &t
|
||||
}
|
||||
return d, nil
|
||||
}
|
||||
|
||||
// versionCount compte les versions d'un fichier et renvoie l'identifiant de la
|
||||
// plus ancienne, sans lire leurs métadonnées.
|
||||
func (s *Store) versionCount(c string) (int, string) {
|
||||
des, err := os.ReadDir(s.historyAbs(c))
|
||||
if err != nil {
|
||||
return 0, ""
|
||||
}
|
||||
n, oldest := 0, ""
|
||||
for _, de := range des {
|
||||
id := de.Name()
|
||||
if de.IsDir() || !versionID.MatchString(id) {
|
||||
continue
|
||||
}
|
||||
n++
|
||||
if oldest == "" || id < oldest {
|
||||
oldest = id
|
||||
}
|
||||
}
|
||||
return n, oldest
|
||||
}
|
||||
|
||||
// dirDetails compte le contenu d'un dossier : éléments directs, puis taille
|
||||
// et nombre de fichiers de toute l'arborescence (borné à maxDirWalk entrées).
|
||||
func (s *Store) dirDetails(rel string) (*Details, error) {
|
||||
_, abs, err := s.resolve(rel)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
des, err := os.ReadDir(abs)
|
||||
if err != nil {
|
||||
return nil, mapErr(err)
|
||||
}
|
||||
d := &Details{}
|
||||
for _, de := range des {
|
||||
if !visible(de.Name()) || de.Type()&os.ModeSymlink != 0 {
|
||||
continue
|
||||
}
|
||||
if de.IsDir() {
|
||||
d.Dirs++
|
||||
} else {
|
||||
d.Files++
|
||||
}
|
||||
}
|
||||
seen := 0
|
||||
_ = filepath.WalkDir(abs, func(p string, e os.DirEntry, err error) error {
|
||||
if err != nil || p == abs {
|
||||
return nil
|
||||
}
|
||||
if strings.HasPrefix(e.Name(), ".") {
|
||||
if e.IsDir() {
|
||||
return filepath.SkipDir
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if seen++; seen > maxDirWalk {
|
||||
return filepath.SkipAll
|
||||
}
|
||||
if e.Type().IsRegular() {
|
||||
if fi, err := e.Info(); err == nil {
|
||||
d.Total += fi.Size()
|
||||
d.Count++
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
return d, nil
|
||||
}
|
||||
|
||||
// shareCounts compte les liens de partage actifs par chemin.
|
||||
func (s *Store) shareCounts() map[string]int {
|
||||
s.sharesMu.Lock()
|
||||
defer s.sharesMu.Unlock()
|
||||
m, err := s.readShares()
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
out := map[string]int{}
|
||||
now := time.Now()
|
||||
for _, d := range m {
|
||||
if d.Expires == nil || now.Before(*d.Expires) {
|
||||
out[d.Path]++
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// noteEdit retient le dernier utilisateur qui a déposé un fichier et, pour un
|
||||
// fichier nouveau, sa date de création et son auteur. .meta.json n'est réécrit
|
||||
// que si quelque chose change.
|
||||
func (s *Store) noteEdit(c, by string, created bool) {
|
||||
if c == "" {
|
||||
return
|
||||
}
|
||||
s.metaMu.Lock()
|
||||
defer s.metaMu.Unlock()
|
||||
if s.loadMeta() != nil {
|
||||
return
|
||||
}
|
||||
m := s.meta[c]
|
||||
changed := false
|
||||
if by != "" && m.EditedBy != by {
|
||||
m.EditedBy, changed = by, true
|
||||
}
|
||||
if created && m.Created == nil {
|
||||
now := time.Now().UTC().Truncate(time.Second)
|
||||
m.Created, m.CreatedBy, changed = &now, by, true
|
||||
}
|
||||
if changed {
|
||||
s.meta[c] = m
|
||||
_ = s.saveMeta()
|
||||
}
|
||||
}
|
||||
|
||||
// AddDetails complète des entrées (chemins virtuels) de leurs détails. Les
|
||||
// dossiers virtuels, favoris cassés et éléments de la poubelle sont laissés
|
||||
// tels quels.
|
||||
func (u *Space) AddDetails(es []*Entry) {
|
||||
metas := map[*Store]map[string]itemMeta{}
|
||||
shares := map[*Store]map[string]int{}
|
||||
for _, e := range es {
|
||||
if e.Special != "" || e.Broken || e.Origin != "" {
|
||||
continue
|
||||
}
|
||||
st, rel, err := u.route(e.Path)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if _, ok := metas[st]; !ok {
|
||||
metas[st], shares[st] = st.metaSnapshot(), st.shareCounts()
|
||||
}
|
||||
if e.IsDir {
|
||||
if d, _ := st.dirDetails(rel); d != nil {
|
||||
d.Shares = shares[st][cleanOr(rel)]
|
||||
e.Details = d
|
||||
}
|
||||
continue
|
||||
}
|
||||
e.Details, _ = st.fileDetails(rel, metas[st], shares[st])
|
||||
}
|
||||
}
|
||||
|
||||
func cleanOr(rel string) string {
|
||||
c, _ := Clean(rel)
|
||||
return c
|
||||
}
|
||||
@@ -0,0 +1,272 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"sort"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Historique des versions : avant qu'un fichier soit remplacé, son contenu
|
||||
// précédent est conservé dans .history/ en miroir de l'arborescence
|
||||
// (a/b.pdf -> .history/a/b.pdf/<date>). La version est un lien physique vers
|
||||
// l'ancien fichier quand le volume le permet (aucune copie de données), sinon
|
||||
// une copie.
|
||||
//
|
||||
// Une version n'est prise que si la précédente date d'au moins
|
||||
// HistoryPolicy.Interval (0 : à chaque remplacement). Restaurer une version ou
|
||||
// en créer une à la demande ignore l'intervalle.
|
||||
|
||||
const historyDir = ".history"
|
||||
|
||||
// HistoryPolicy règle la prise et la rétention des versions.
|
||||
type HistoryPolicy struct {
|
||||
Keep int // versions conservées par fichier (0 : historique désactivé)
|
||||
Interval time.Duration // écart minimal entre deux versions automatiques
|
||||
MaxAge time.Duration // âge maximal d'une version (0 : illimité)
|
||||
}
|
||||
|
||||
// DefaultHistory : 10 versions par fichier, une à chaque remplacement.
|
||||
var DefaultHistory = HistoryPolicy{Keep: 10}
|
||||
|
||||
// Version décrit une version enregistrée d'un fichier. Time est la date à
|
||||
// laquelle ce contenu avait été déposé.
|
||||
type Version struct {
|
||||
ID string `json:"id"`
|
||||
Time time.Time `json:"time"`
|
||||
Size int64 `json:"size"`
|
||||
}
|
||||
|
||||
const versionLayout = "20060102T150405.000000000Z"
|
||||
|
||||
var versionID = regexp.MustCompile(`^\d{8}T\d{6}\.\d{9}Z$`)
|
||||
|
||||
func (s *Store) historyAbs(c string) string {
|
||||
return filepath.Join(s.root, historyDir, filepath.FromSlash(c))
|
||||
}
|
||||
|
||||
func (s *Store) versionAbs(c, id string) string { return filepath.Join(s.historyAbs(c), id) }
|
||||
|
||||
// versions liste les versions d'un fichier, la plus récente en premier.
|
||||
// taken renvoie en plus la date de prise de la plus récente (date du fichier).
|
||||
func (s *Store) versions(c string) ([]Version, time.Time, error) {
|
||||
des, err := os.ReadDir(s.historyAbs(c))
|
||||
if errors.Is(err, fs.ErrNotExist) {
|
||||
return []Version{}, time.Time{}, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, time.Time{}, err
|
||||
}
|
||||
out := []Version{}
|
||||
var taken time.Time
|
||||
for _, de := range des {
|
||||
id := de.Name()
|
||||
if de.IsDir() || !versionID.MatchString(id) {
|
||||
continue
|
||||
}
|
||||
t, err := time.Parse(versionLayout, id)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
fi, err := de.Info()
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
out = append(out, Version{ID: id, Time: t, Size: fi.Size()})
|
||||
if ct := changeTime(fi); ct.After(taken) {
|
||||
taken = ct
|
||||
}
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool { return out[i].ID > out[j].ID })
|
||||
return out, taken, nil
|
||||
}
|
||||
|
||||
// changeTime : date de prise d'une version. Un lien physique garde la date du
|
||||
// contenu : on utilise la date de création de l'entrée d'historique, que le
|
||||
// nom de fichier ne porte pas ; à défaut, la date du contenu.
|
||||
func changeTime(fi fs.FileInfo) time.Time { return fi.ModTime() }
|
||||
|
||||
// snapshot conserve le fichier abs (daté de mod) comme version. Sans force,
|
||||
// rien n'est pris si la dernière version a moins de Interval. Une version
|
||||
// de même date et de même taille que la plus récente n'est jamais dupliquée.
|
||||
func (s *Store) snapshot(c, abs string, fi fs.FileInfo, force bool) (Version, error) {
|
||||
p := s.History
|
||||
if p.Keep <= 0 {
|
||||
return Version{}, nil
|
||||
}
|
||||
vs, _, err := s.versions(c)
|
||||
if err != nil {
|
||||
return Version{}, err
|
||||
}
|
||||
if !force && len(vs) > 0 && p.Interval > 0 && time.Since(vs[0].Time) < p.Interval {
|
||||
return Version{}, nil
|
||||
}
|
||||
v := Version{ID: fi.ModTime().UTC().Format(versionLayout), Time: fi.ModTime().UTC(), Size: fi.Size()}
|
||||
if len(vs) > 0 && vs[0].ID == v.ID && vs[0].Size == v.Size {
|
||||
return vs[0], nil
|
||||
}
|
||||
dst := s.versionAbs(c, v.ID)
|
||||
if err := os.MkdirAll(filepath.Dir(dst), 0o755); err != nil {
|
||||
return Version{}, err
|
||||
}
|
||||
_ = os.Remove(dst)
|
||||
if err := os.Link(abs, dst); err != nil {
|
||||
if err := copyFile(abs, dst); err != nil {
|
||||
return Version{}, err
|
||||
}
|
||||
_ = os.Chtimes(dst, fi.ModTime(), fi.ModTime())
|
||||
}
|
||||
s.pruneHistory(c)
|
||||
return v, nil
|
||||
}
|
||||
|
||||
// pruneHistory applique la rétention (nombre et âge) aux versions d'un fichier.
|
||||
func (s *Store) pruneHistory(c string) {
|
||||
vs, _, err := s.versions(c)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
for i, v := range vs {
|
||||
if i >= s.History.Keep || (s.History.MaxAge > 0 && time.Since(v.Time) > s.History.MaxAge) {
|
||||
_ = os.Remove(s.versionAbs(c, v.ID))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// autoSnapshot est appelé par Put avant de remplacer un fichier ; un échec est
|
||||
// journalisé mais n'empêche pas l'enregistrement.
|
||||
func (s *Store) autoSnapshot(c, abs string, fi fs.FileInfo) {
|
||||
if _, err := s.snapshot(c, abs, fi, false); err != nil {
|
||||
slog.Warn("historique : version non enregistrée", "path", c, "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Versions liste les versions d'un fichier existant, la plus récente en premier.
|
||||
func (s *Store) Versions(rel string) ([]Version, error) {
|
||||
c, abs, err := s.resolve(rel)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if c == "" {
|
||||
return nil, ErrInvalidPath
|
||||
}
|
||||
if fi, err := os.Lstat(abs); err != nil || !fi.Mode().IsRegular() {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
vs, _, err := s.versions(c)
|
||||
return vs, err
|
||||
}
|
||||
|
||||
// OpenVersion ouvre une version en lecture.
|
||||
func (s *Store) OpenVersion(rel, id string) (*os.File, fs.FileInfo, error) {
|
||||
c, _, err := s.resolve(rel)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if c == "" || !versionID.MatchString(id) {
|
||||
return nil, nil, fmt.Errorf("%w : version %q", ErrInvalidPath, id)
|
||||
}
|
||||
f, err := os.Open(s.versionAbs(c, id))
|
||||
if err != nil {
|
||||
return nil, nil, mapErr(err)
|
||||
}
|
||||
fi, err := f.Stat()
|
||||
if err != nil {
|
||||
f.Close()
|
||||
return nil, nil, err
|
||||
}
|
||||
return f, fi, nil
|
||||
}
|
||||
|
||||
// Snapshot crée une version du contenu courant, quel que soit l'intervalle.
|
||||
func (s *Store) Snapshot(rel string) (Version, error) {
|
||||
c, abs, err := s.resolve(rel)
|
||||
if err != nil {
|
||||
return Version{}, err
|
||||
}
|
||||
if s.History.Keep <= 0 {
|
||||
return Version{}, fmt.Errorf("%w : historique désactivé (HISTORY_KEEP=0)", ErrInvalidPath)
|
||||
}
|
||||
fi, err := os.Lstat(abs)
|
||||
if err != nil || !fi.Mode().IsRegular() {
|
||||
return Version{}, ErrNotFound
|
||||
}
|
||||
return s.snapshot(c, abs, fi, true)
|
||||
}
|
||||
|
||||
// Restore remplace le contenu d'un fichier par une de ses versions. Le contenu
|
||||
// courant est d'abord enregistré comme version : une restauration s'annule.
|
||||
func (s *Store) Restore(rel, id string) (Entry, error) {
|
||||
vf, _, err := s.OpenVersion(rel, id)
|
||||
if err != nil {
|
||||
return Entry{}, err
|
||||
}
|
||||
defer vf.Close()
|
||||
c, abs, _ := s.resolve(rel)
|
||||
fi, err := os.Lstat(abs)
|
||||
if err != nil || !fi.Mode().IsRegular() {
|
||||
return Entry{}, ErrNotFound
|
||||
}
|
||||
vfi, _ := vf.Stat()
|
||||
tmp, err := os.CreateTemp(filepath.Dir(abs), ".tmp-*")
|
||||
if err != nil {
|
||||
return Entry{}, err
|
||||
}
|
||||
defer os.Remove(tmp.Name())
|
||||
if _, err := io.Copy(tmp, vf); err != nil {
|
||||
tmp.Close()
|
||||
return Entry{}, err
|
||||
}
|
||||
if err := tmp.Close(); err != nil {
|
||||
return Entry{}, err
|
||||
}
|
||||
_ = os.Chmod(tmp.Name(), 0o644)
|
||||
if vfi != nil {
|
||||
_ = os.Chtimes(tmp.Name(), vfi.ModTime(), vfi.ModTime())
|
||||
}
|
||||
if _, err := s.snapshot(c, abs, fi, true); err != nil {
|
||||
return Entry{}, err
|
||||
}
|
||||
if err := os.Rename(tmp.Name(), abs); err != nil {
|
||||
return Entry{}, err
|
||||
}
|
||||
s.usageDirty()
|
||||
s.removeThumb(c)
|
||||
nfi, err := os.Stat(abs)
|
||||
if err != nil {
|
||||
return Entry{}, err
|
||||
}
|
||||
return toEntry(c, nfi), nil
|
||||
}
|
||||
|
||||
// Les opérations suivantes accompagnent Move/Delete.
|
||||
|
||||
func (s *Store) moveHistory(from, to string) {
|
||||
src, dst := s.historyAbs(from), s.historyAbs(to)
|
||||
if _, err := os.Stat(src); err != nil {
|
||||
return
|
||||
}
|
||||
_ = os.RemoveAll(dst)
|
||||
if err := os.MkdirAll(filepath.Dir(dst), 0o755); err == nil {
|
||||
_ = os.Rename(src, dst)
|
||||
}
|
||||
}
|
||||
|
||||
// trashHistory range l'historique d'un élément supprimé avec lui dans la
|
||||
// corbeille (trash/.history/<nom>), pour pouvoir le récupérer à la main.
|
||||
func (s *Store) trashHistory(c, trash string) {
|
||||
src := s.historyAbs(c)
|
||||
if _, err := os.Stat(src); err != nil {
|
||||
return
|
||||
}
|
||||
dst := filepath.Join(trash, historyDir, filepath.Base(src))
|
||||
if err := os.MkdirAll(filepath.Dir(dst), 0o755); err == nil {
|
||||
_ = os.Rename(src, dst)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,330 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// Tags et favoris des fichiers et dossiers, et icône des dossiers, dans
|
||||
// .meta.json à la racine :
|
||||
// {"items":{"a/b.pdf":{"tags":["NSX"],"favorite":true},"a":{"icon":"server"}}}.
|
||||
// Ils suivent les renommages, déplacements et suppressions. Les fichiers y
|
||||
// gardent aussi leur auteur et leur date de création, et le dernier
|
||||
// utilisateur qui les a enregistrés (details.go).
|
||||
|
||||
const metaFile = ".meta.json"
|
||||
|
||||
const (
|
||||
// MaxTagLen borne la longueur d'un tag (en caractères).
|
||||
MaxTagLen = 40
|
||||
// MaxTags borne le nombre de tags d'un élément.
|
||||
MaxTags = 20
|
||||
)
|
||||
|
||||
type itemMeta struct {
|
||||
Tags []string `json:"tags,omitempty"`
|
||||
Favorite bool `json:"favorite,omitempty"`
|
||||
Icon string `json:"icon,omitempty"` // dossiers : nom d'icône du frontend
|
||||
|
||||
// Schémas (details.go) : création et dernier enregistrement.
|
||||
Created *time.Time `json:"created,omitempty"`
|
||||
CreatedBy string `json:"createdBy,omitempty"`
|
||||
EditedBy string `json:"editedBy,omitempty"`
|
||||
}
|
||||
|
||||
func (m itemMeta) empty() bool {
|
||||
return len(m.Tags) == 0 && !m.Favorite && m.Icon == "" && m.Created == nil && m.CreatedBy == "" && m.EditedBy == ""
|
||||
}
|
||||
|
||||
// iconName : nom d'icône accepté (le frontend affiche le dossier classique
|
||||
// pour un nom qu'il ne connaît pas).
|
||||
var iconName = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{0,31}$`)
|
||||
|
||||
// TagCount est un tag utilisé et son nombre d'éléments.
|
||||
type TagCount struct {
|
||||
Name string `json:"name"`
|
||||
Count int `json:"count"`
|
||||
}
|
||||
|
||||
// loadMeta charge .meta.json au premier accès ; appelé sous metaMu.
|
||||
func (s *Store) loadMeta() error {
|
||||
if s.meta != nil {
|
||||
return nil
|
||||
}
|
||||
var d struct {
|
||||
Items map[string]itemMeta `json:"items"`
|
||||
}
|
||||
b, err := os.ReadFile(filepath.Join(s.root, metaFile))
|
||||
switch {
|
||||
case errors.Is(err, fs.ErrNotExist):
|
||||
case err != nil:
|
||||
return err
|
||||
default:
|
||||
if err := json.Unmarshal(b, &d); err != nil {
|
||||
return fmt.Errorf("%s : %w", metaFile, err)
|
||||
}
|
||||
}
|
||||
if d.Items == nil {
|
||||
d.Items = map[string]itemMeta{}
|
||||
}
|
||||
s.meta = d.Items
|
||||
return nil
|
||||
}
|
||||
|
||||
// saveMeta écrit .meta.json ; appelé sous metaMu.
|
||||
func (s *Store) saveMeta() error {
|
||||
for k, m := range s.meta {
|
||||
if m.empty() {
|
||||
delete(s.meta, k)
|
||||
}
|
||||
}
|
||||
b, err := json.Marshal(map[string]any{"items": s.meta})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return atomicWrite(filepath.Join(s.root, metaFile), b)
|
||||
}
|
||||
|
||||
// metaSnapshot renvoie une copie des métadonnées (pour List et Search).
|
||||
func (s *Store) metaSnapshot() map[string]itemMeta {
|
||||
s.metaMu.Lock()
|
||||
defer s.metaMu.Unlock()
|
||||
if s.loadMeta() != nil {
|
||||
return map[string]itemMeta{}
|
||||
}
|
||||
out := make(map[string]itemMeta, len(s.meta))
|
||||
for k, v := range s.meta {
|
||||
out[k] = v
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func decorate(e *Entry, meta map[string]itemMeta) {
|
||||
if m, ok := meta[e.Path]; ok {
|
||||
e.Tags, e.Favorite = m.Tags, m.Favorite
|
||||
if e.IsDir {
|
||||
e.Icon = m.Icon
|
||||
} else {
|
||||
e.EditedBy = m.EditedBy
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func normTag(t string) (string, error) {
|
||||
t = strings.Join(strings.Fields(strings.TrimPrefix(strings.TrimSpace(t), "#")), " ")
|
||||
switch {
|
||||
case t == "", !utf8.ValidString(t), strings.ContainsAny(t, ",\x00"):
|
||||
return "", fmt.Errorf("%w : tag %q", ErrInvalidPath, t)
|
||||
case utf8.RuneCountInString(t) > MaxTagLen:
|
||||
return "", fmt.Errorf("%w : tag de %d caractères max", ErrInvalidPath, MaxTagLen)
|
||||
}
|
||||
return t, nil
|
||||
}
|
||||
|
||||
// editMeta vérifie que chaque chemin existe puis applique edit à ses
|
||||
// métadonnées, et enregistre le tout.
|
||||
func (s *Store) editMeta(paths []string, edit func(*itemMeta) error) error {
|
||||
cs := make([]string, 0, len(paths))
|
||||
for _, p := range paths {
|
||||
c, abs, err := s.resolve(p)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if c == "" {
|
||||
return ErrInvalidPath
|
||||
}
|
||||
if _, err := os.Lstat(abs); err != nil {
|
||||
return mapErr(err)
|
||||
}
|
||||
cs = append(cs, c)
|
||||
}
|
||||
s.metaMu.Lock()
|
||||
defer s.metaMu.Unlock()
|
||||
if err := s.loadMeta(); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, c := range cs {
|
||||
m := s.meta[c]
|
||||
m.Tags = append([]string(nil), m.Tags...)
|
||||
if err := edit(&m); err != nil {
|
||||
return err
|
||||
}
|
||||
s.meta[c] = m
|
||||
}
|
||||
return s.saveMeta()
|
||||
}
|
||||
|
||||
// SetFavorite ajoute ou retire des éléments des favoris.
|
||||
func (s *Store) SetFavorite(paths []string, favorite bool) error {
|
||||
return s.editMeta(paths, func(m *itemMeta) error {
|
||||
m.Favorite = favorite
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// SetIcon choisit l'icône de dossiers ; icon = "" rétablit l'icône par défaut.
|
||||
func (s *Store) SetIcon(paths []string, icon string) error {
|
||||
if icon != "" && !iconName.MatchString(icon) {
|
||||
return fmt.Errorf("%w : icône %q", ErrInvalidPath, icon)
|
||||
}
|
||||
for _, p := range paths {
|
||||
_, abs, err := s.resolve(p)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if fi, err := os.Lstat(abs); err != nil {
|
||||
return mapErr(err)
|
||||
} else if !fi.IsDir() {
|
||||
return fmt.Errorf("%w : %q n'est pas un dossier", ErrInvalidPath, p)
|
||||
}
|
||||
}
|
||||
return s.editMeta(paths, func(m *itemMeta) error {
|
||||
m.Icon = icon
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// EditTags ajoute et retire des tags sur des éléments. Les tags sont comparés
|
||||
// sans casse ni accents ; un tag déjà utilisé garde son écriture d'origine.
|
||||
func (s *Store) EditTags(paths, add, remove []string) error {
|
||||
var adds []string
|
||||
for _, t := range add {
|
||||
n, err := normTag(t)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
adds = append(adds, n)
|
||||
}
|
||||
drop := map[string]bool{}
|
||||
for _, t := range remove {
|
||||
drop[fold(strings.TrimSpace(t))] = true
|
||||
}
|
||||
canon := map[string]string{} // écriture existante de chaque tag
|
||||
s.metaMu.Lock()
|
||||
err := s.loadMeta()
|
||||
for _, m := range s.meta {
|
||||
for _, t := range m.Tags {
|
||||
if _, ok := canon[fold(t)]; !ok {
|
||||
canon[fold(t)] = t
|
||||
}
|
||||
}
|
||||
}
|
||||
s.metaMu.Unlock()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return s.editMeta(paths, func(m *itemMeta) error {
|
||||
kept := m.Tags[:0]
|
||||
has := map[string]bool{}
|
||||
for _, t := range m.Tags {
|
||||
if !drop[fold(t)] && !has[fold(t)] {
|
||||
kept = append(kept, t)
|
||||
has[fold(t)] = true
|
||||
}
|
||||
}
|
||||
for _, t := range adds {
|
||||
if has[fold(t)] {
|
||||
continue
|
||||
}
|
||||
if c, ok := canon[fold(t)]; ok {
|
||||
t = c
|
||||
}
|
||||
kept = append(kept, t)
|
||||
has[fold(t)] = true
|
||||
}
|
||||
if len(kept) > MaxTags {
|
||||
return fmt.Errorf("%w : %d tags max par élément", ErrInvalidPath, MaxTags)
|
||||
}
|
||||
sort.Slice(kept, func(i, j int) bool { return fold(kept[i]) < fold(kept[j]) })
|
||||
m.Tags = kept
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// Tags liste les tags utilisés, triés par nom, avec leur nombre d'éléments.
|
||||
func (s *Store) Tags() ([]TagCount, error) {
|
||||
s.metaMu.Lock()
|
||||
defer s.metaMu.Unlock()
|
||||
if err := s.loadMeta(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
idx := map[string]int{}
|
||||
out := []TagCount{}
|
||||
for _, m := range s.meta {
|
||||
for _, t := range m.Tags {
|
||||
k := fold(t)
|
||||
if i, ok := idx[k]; ok {
|
||||
out[i].Count++
|
||||
} else {
|
||||
idx[k] = len(out)
|
||||
out = append(out, TagCount{Name: t, Count: 1})
|
||||
}
|
||||
}
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool { return fold(out[i].Name) < fold(out[j].Name) })
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// Les opérations suivantes accompagnent Move/Copy/Delete (au mieux).
|
||||
|
||||
func under(k, c string) bool { return k == c || strings.HasPrefix(k, c+"/") }
|
||||
|
||||
func (s *Store) moveMeta(from, to string) {
|
||||
s.metaMu.Lock()
|
||||
defer s.metaMu.Unlock()
|
||||
if s.loadMeta() != nil {
|
||||
return
|
||||
}
|
||||
moved := map[string]itemMeta{}
|
||||
for k, m := range s.meta {
|
||||
if under(k, from) {
|
||||
delete(s.meta, k)
|
||||
moved[to+k[len(from):]] = m
|
||||
}
|
||||
}
|
||||
for k, m := range moved {
|
||||
s.meta[k] = m
|
||||
}
|
||||
if len(moved) > 0 {
|
||||
_ = s.saveMeta()
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Store) copyMeta(from, to string) {
|
||||
s.metaMu.Lock()
|
||||
defer s.metaMu.Unlock()
|
||||
if s.loadMeta() != nil {
|
||||
return
|
||||
}
|
||||
if m, ok := s.meta[from]; ok && len(m.Tags) > 0 {
|
||||
s.meta[to] = itemMeta{Tags: append([]string(nil), m.Tags...)} // pas le favori
|
||||
_ = s.saveMeta()
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Store) removeMeta(c string) {
|
||||
s.metaMu.Lock()
|
||||
defer s.metaMu.Unlock()
|
||||
if s.loadMeta() != nil {
|
||||
return
|
||||
}
|
||||
changed := false
|
||||
for k := range s.meta {
|
||||
if under(k, c) {
|
||||
delete(s.meta, k)
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
if changed {
|
||||
_ = s.saveMeta()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"io/fs"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// Recherche plein texte : noms des fichiers et dossiers, tags, et contenu des
|
||||
// fichiers texte de moins de 512 Ko (notes, configurations, code, journaux...).
|
||||
// Le texte de chaque fichier est lu une fois puis gardé en mémoire tant que le
|
||||
// fichier ne change pas (date et taille) : seule la première recherche lit tous
|
||||
// les fichiers texte, les suivantes ne relisent que ceux modifiés.
|
||||
|
||||
// Hit est un résultat de recherche. Snippet est l'extrait du contenu qui
|
||||
// correspond (vide si seul le nom correspond).
|
||||
type Hit struct {
|
||||
Entry
|
||||
Snippet string `json:"snippet,omitempty"`
|
||||
}
|
||||
|
||||
type indexDoc struct {
|
||||
mod time.Time
|
||||
size int64
|
||||
text string // texte extrait
|
||||
fold string // texte normalisé (minuscules, sans accents), même nombre de runes
|
||||
}
|
||||
|
||||
type textIndex struct {
|
||||
mu sync.Mutex
|
||||
docs map[string]indexDoc
|
||||
}
|
||||
|
||||
// fold met en minuscules et retire les accents des lettres latines courantes,
|
||||
// rune pour rune : la position d'une correspondance vaut pour le texte d'origine.
|
||||
func fold(s string) string {
|
||||
return strings.Map(func(r rune) rune {
|
||||
r = unicode.ToLower(r)
|
||||
if f, ok := foldMap[r]; ok {
|
||||
return f
|
||||
}
|
||||
return r
|
||||
}, s)
|
||||
}
|
||||
|
||||
var foldMap = func() map[rune]rune {
|
||||
m := map[rune]rune{}
|
||||
for base, accented := range map[rune]string{
|
||||
'a': "àáâãäåāăą", 'c': "çćĉċč", 'd': "ď", 'e': "èéêëēĕėęě", 'g': "ĝğġģ",
|
||||
'i': "ìíîïĩīĭįı", 'n': "ñńņňʼn", 'o': "òóôõöøōŏő", 'r': "ŕŗř", 's': "śŝşš",
|
||||
't': "ţťŧ", 'u': "ùúûüũūŭůűų", 'y': "ýÿŷ", 'z': "źżž",
|
||||
} {
|
||||
for _, r := range accented {
|
||||
m[r] = base
|
||||
}
|
||||
}
|
||||
return m
|
||||
}()
|
||||
|
||||
// maxIndexedSize borne la taille d'un fichier dont le contenu est indexé.
|
||||
const maxIndexedSize = 512 << 10
|
||||
|
||||
// textExts : extensions de fichiers dont le contenu est du texte indexé.
|
||||
var textExts = map[string]bool{
|
||||
".txt": true, ".md": true, ".markdown": true, ".rst": true, ".log": true, ".csv": true, ".tsv": true,
|
||||
".json": true, ".yaml": true, ".yml": true, ".toml": true, ".ini": true, ".conf": true, ".cfg": true,
|
||||
".env": true, ".xml": true, ".html": true, ".htm": true, ".css": true, ".js": true, ".mjs": true,
|
||||
".ts": true, ".tsx": true, ".jsx": true, ".py": true, ".go": true, ".rs": true, ".java": true,
|
||||
".c": true, ".h": true, ".cpp": true, ".hpp": true, ".cs": true, ".php": true, ".rb": true,
|
||||
".sh": true, ".bash": true, ".zsh": true, ".ps1": true, ".sql": true, ".tf": true, ".lua": true,
|
||||
".service": true, ".sub": true, ".srt": true, ".tex": true, ".bib": true, ".gitignore": true,
|
||||
}
|
||||
|
||||
// IsText indique si le contenu d'un fichier est indexé et prévisualisé comme du texte.
|
||||
func IsText(name string) bool {
|
||||
ext := strings.ToLower(path.Ext(name))
|
||||
if ext == "" {
|
||||
switch strings.ToLower(path.Base(name)) {
|
||||
case "dockerfile", "makefile", "readme", "license", "changelog":
|
||||
return true
|
||||
}
|
||||
}
|
||||
return textExts[ext]
|
||||
}
|
||||
|
||||
// extractText renvoie le texte d'un fichier indexable (vide si ce n'en est pas un).
|
||||
func extractText(abs string, fi fs.FileInfo) string {
|
||||
if !IsText(fi.Name()) || fi.Size() > maxIndexedSize {
|
||||
return ""
|
||||
}
|
||||
b, err := os.ReadFile(abs)
|
||||
if err != nil || !utf8.Valid(b) {
|
||||
return ""
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
|
||||
// content renvoie le texte indexé d'un fichier, relu seulement s'il a changé ;
|
||||
// appelé sous index.mu.
|
||||
func (s *Store) content(rel, abs string, fi fs.FileInfo) indexDoc {
|
||||
d, ok := s.index.docs[rel]
|
||||
if ok && d.mod.Equal(fi.ModTime()) && d.size == fi.Size() {
|
||||
return d
|
||||
}
|
||||
d = indexDoc{mod: fi.ModTime(), size: fi.Size()}
|
||||
d.text = extractText(abs, fi)
|
||||
d.fold = fold(d.text)
|
||||
s.index.docs[rel] = d
|
||||
return d
|
||||
}
|
||||
|
||||
// snippet renvoie la ligne du texte qui contient la position i (en octets
|
||||
// de fold), raccourcie autour de la correspondance.
|
||||
func snippet(d indexDoc, i, n int) string {
|
||||
runes := []rune(d.text)
|
||||
at := utf8.RuneCountInString(d.fold[:i])
|
||||
end := at + utf8.RuneCountInString(d.fold[i:i+n])
|
||||
lo, hi := at, end
|
||||
for lo > 0 && runes[lo-1] != '\n' {
|
||||
lo--
|
||||
}
|
||||
for hi < len(runes) && runes[hi] != '\n' {
|
||||
hi++
|
||||
}
|
||||
const ctx = 40
|
||||
pre, post := "", ""
|
||||
if at-lo > ctx {
|
||||
lo, pre = at-ctx, "…"
|
||||
}
|
||||
if hi-end > ctx {
|
||||
hi, post = end+ctx, "…"
|
||||
}
|
||||
return pre + string(runes[lo:hi]) + post
|
||||
}
|
||||
|
||||
// Filter restreint une recherche aux éléments portant un tag ou favoris.
|
||||
type Filter struct {
|
||||
Tag string
|
||||
Favorite bool
|
||||
}
|
||||
|
||||
// Search renvoie les entrées dont le nom, les tags ou, pour un fichier, le
|
||||
// contenu contiennent tous les mots de q (casse et accents ignorés), et qui
|
||||
// passent le filtre. Les correspondances sur le nom viennent en premier.
|
||||
// q peut être vide si un filtre est donné.
|
||||
func (s *Store) Search(q string, f Filter, limit int) ([]Hit, error) {
|
||||
terms := strings.Fields(fold(q))
|
||||
tag := fold(strings.TrimSpace(strings.TrimPrefix(strings.TrimSpace(f.Tag), "#")))
|
||||
if len(terms) == 0 && tag == "" && !f.Favorite {
|
||||
return []Hit{}, nil
|
||||
}
|
||||
meta := s.metaSnapshot()
|
||||
s.index.mu.Lock()
|
||||
defer s.index.mu.Unlock()
|
||||
if s.index.docs == nil {
|
||||
s.index.docs = map[string]indexDoc{}
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
var byName, byContent []Hit
|
||||
err := filepath.WalkDir(s.root, func(p string, d fs.DirEntry, err error) error {
|
||||
if err != nil || p == s.root {
|
||||
return nil
|
||||
}
|
||||
if strings.HasPrefix(d.Name(), ".") {
|
||||
if d.IsDir() {
|
||||
return filepath.SkipDir
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if d.Type()&fs.ModeSymlink != 0 || (!d.IsDir() && !d.Type().IsRegular()) {
|
||||
return nil
|
||||
}
|
||||
fi, err := d.Info()
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
rel, err := filepath.Rel(s.root, p)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
rel = filepath.ToSlash(rel)
|
||||
hit := Hit{Entry: toEntry(rel, fi)}
|
||||
decorate(&hit.Entry, meta)
|
||||
if f.Favorite && !hit.Favorite {
|
||||
return nil
|
||||
}
|
||||
tags := fold(strings.Join(hit.Tags, "\n"))
|
||||
if tag != "" && !strings.Contains("\n"+tags+"\n", "\n"+tag+"\n") {
|
||||
return nil
|
||||
}
|
||||
name := fold(d.Name()) + "\n" + tags
|
||||
var doc indexDoc
|
||||
if !d.IsDir() {
|
||||
seen[rel] = true
|
||||
if len(terms) > 0 {
|
||||
doc = s.content(rel, p, fi)
|
||||
}
|
||||
}
|
||||
inName := true
|
||||
for _, t := range terms {
|
||||
if strings.Contains(name, t) {
|
||||
continue
|
||||
}
|
||||
inName = false
|
||||
i := strings.Index(doc.fold, t)
|
||||
if i < 0 {
|
||||
return nil
|
||||
}
|
||||
if hit.Snippet == "" {
|
||||
hit.Snippet = snippet(doc, i, len(t))
|
||||
}
|
||||
}
|
||||
if inName {
|
||||
byName = append(byName, hit)
|
||||
} else {
|
||||
byContent = append(byContent, hit)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for rel := range s.index.docs {
|
||||
if !seen[rel] {
|
||||
delete(s.index.docs, rel) // fichier supprimé ou déplacé
|
||||
}
|
||||
}
|
||||
out := append(byName, byContent...)
|
||||
if len(out) > limit {
|
||||
out = out[:limit]
|
||||
}
|
||||
if out == nil {
|
||||
out = []Hit{}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -0,0 +1,294 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"image"
|
||||
"image/draw"
|
||||
"image/png"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// Paramètres partagés par tous les navigateurs : .settings.json et .logo.png à
|
||||
// la racine. Les valeurs que l'administrateur n'a pas modifiées viennent des
|
||||
// variables d'environnement (SettingsDefaults).
|
||||
|
||||
const (
|
||||
settingsFile = ".settings.json"
|
||||
logoFile = ".logo.png"
|
||||
|
||||
// LogoSize est le côté du logo enregistré (carré, affiché en rond).
|
||||
LogoSize = 64
|
||||
// MaxLogoUpload borne la taille d'un PNG envoyé avant redimensionnement.
|
||||
MaxLogoUpload = 5 << 20
|
||||
// MaxTitleLen borne la longueur du titre (en caractères).
|
||||
MaxTitleLen = 80
|
||||
// MaxTrashDays borne la durée de conservation de la corbeille (en jours).
|
||||
MaxTrashDays = 3650
|
||||
// MaxQuotaMB borne le quota par utilisateur (Mo).
|
||||
MaxQuotaMB = 100 << 20
|
||||
|
||||
maxLogoSide = 8192 // protège contre les « bombes » de décompression
|
||||
)
|
||||
|
||||
// ErrInvalidImage signale un logo illisible ou hors limites.
|
||||
var ErrInvalidImage = errors.New("image invalide")
|
||||
|
||||
// Modes d'inscription (Settings.Registration).
|
||||
const (
|
||||
RegClosed = "closed" // pas d'inscription : l'administrateur crée les comptes
|
||||
RegApproval = "approval" // inscription libre, compte à valider par un administrateur
|
||||
RegOpen = "open" // inscription libre, compte actif tout de suite
|
||||
)
|
||||
|
||||
// ValidRegistration indique si m est un mode d'inscription connu.
|
||||
func ValidRegistration(m string) bool { return m == RegClosed || m == RegApproval || m == RegOpen }
|
||||
|
||||
// SettingsDefaults : valeurs des paramètres tant qu'ils n'ont pas été modifiés.
|
||||
type SettingsDefaults struct {
|
||||
Registration string // closed, approval ou open
|
||||
QuotaMB int64 // quota de l'espace personnel par utilisateur (0 : illimité)
|
||||
CommonReadonly bool // arborescence commune en lecture seule pour les non-administrateurs
|
||||
TrashDays int
|
||||
}
|
||||
|
||||
// DefaultSettings : inscription fermée, pas de quota, commun ouvert en écriture.
|
||||
var DefaultSettings = SettingsDefaults{Registration: RegClosed}
|
||||
|
||||
// Settings est l'état exposé au client. Logo vaut "" sans logo, sinon une
|
||||
// version (date) à ajouter à l'URL pour invalider le cache navigateur.
|
||||
// TrashDays : durée de conservation de la corbeille (0 : jusqu'à ce qu'on la
|
||||
// vide). QuotaMB : quota de l'espace personnel (0 : illimité).
|
||||
type Settings struct {
|
||||
Title string `json:"title"`
|
||||
Logo string `json:"logo"`
|
||||
TrashDays int `json:"trashDays"`
|
||||
Registration string `json:"registration"`
|
||||
QuotaMB int64 `json:"quotaMB"`
|
||||
CommonReadonly bool `json:"commonReadonly"`
|
||||
}
|
||||
|
||||
type settingsDisk struct {
|
||||
Title string `json:"title"`
|
||||
TrashDays *int `json:"trashDays,omitempty"`
|
||||
Registration *string `json:"registration,omitempty"`
|
||||
QuotaMB *int64 `json:"quotaMB,omitempty"`
|
||||
CommonReadonly *bool `json:"commonReadonly,omitempty"`
|
||||
}
|
||||
|
||||
func (s *Store) readSettingsDisk() (settingsDisk, error) {
|
||||
var d settingsDisk
|
||||
b, err := os.ReadFile(filepath.Join(s.root, settingsFile))
|
||||
switch {
|
||||
case errors.Is(err, fs.ErrNotExist):
|
||||
case err != nil:
|
||||
return d, err
|
||||
default:
|
||||
if err := json.Unmarshal(b, &d); err != nil {
|
||||
return d, fmt.Errorf("%s : %w", settingsFile, err)
|
||||
}
|
||||
}
|
||||
return d, nil
|
||||
}
|
||||
|
||||
// updateSettings applique edit au fichier de paramètres (lecture, modification,
|
||||
// écriture atomique) sous le verrou du Store.
|
||||
func (s *Store) updateSettings(edit func(*settingsDisk)) (Settings, error) {
|
||||
s.settingsMu.Lock()
|
||||
defer s.settingsMu.Unlock()
|
||||
d, err := s.readSettingsDisk()
|
||||
if err != nil {
|
||||
return Settings{}, err
|
||||
}
|
||||
edit(&d)
|
||||
b, err := json.Marshal(d)
|
||||
if err != nil {
|
||||
return Settings{}, err
|
||||
}
|
||||
if err := atomicWrite(filepath.Join(s.root, settingsFile), b); err != nil {
|
||||
return Settings{}, err
|
||||
}
|
||||
return s.readSettings()
|
||||
}
|
||||
|
||||
// ReadSettings renvoie les paramètres courants (valeurs par défaut si absents).
|
||||
func (s *Store) ReadSettings() (Settings, error) {
|
||||
s.settingsMu.Lock()
|
||||
defer s.settingsMu.Unlock()
|
||||
return s.readSettings()
|
||||
}
|
||||
|
||||
func (s *Store) readSettings() (Settings, error) {
|
||||
d, err := s.readSettingsDisk()
|
||||
if err != nil {
|
||||
return Settings{}, err
|
||||
}
|
||||
def := s.Defaults
|
||||
if !ValidRegistration(def.Registration) {
|
||||
def.Registration = RegClosed
|
||||
}
|
||||
st := Settings{Title: d.Title, TrashDays: def.TrashDays, Registration: def.Registration,
|
||||
QuotaMB: def.QuotaMB, CommonReadonly: def.CommonReadonly}
|
||||
if d.TrashDays != nil {
|
||||
st.TrashDays = *d.TrashDays
|
||||
}
|
||||
if d.Registration != nil && ValidRegistration(*d.Registration) {
|
||||
st.Registration = *d.Registration
|
||||
}
|
||||
if d.QuotaMB != nil {
|
||||
st.QuotaMB = *d.QuotaMB
|
||||
}
|
||||
if d.CommonReadonly != nil {
|
||||
st.CommonReadonly = *d.CommonReadonly
|
||||
}
|
||||
if fi, err := os.Stat(filepath.Join(s.root, logoFile)); err == nil {
|
||||
st.Logo = strconv.FormatInt(fi.ModTime().UnixNano(), 36)
|
||||
}
|
||||
return st, nil
|
||||
}
|
||||
|
||||
// WriteTrashDays règle la purge automatique de la corbeille (0 : désactivée).
|
||||
func (s *Store) WriteTrashDays(days int) (Settings, error) {
|
||||
if days < 0 || days > MaxTrashDays {
|
||||
return Settings{}, fmt.Errorf("%w : durée de 0 à %d jours", ErrInvalidPath, MaxTrashDays)
|
||||
}
|
||||
return s.updateSettings(func(d *settingsDisk) { d.TrashDays = &days })
|
||||
}
|
||||
|
||||
// WriteRegistration choisit le mode d'inscription (closed, approval, open).
|
||||
func (s *Store) WriteRegistration(mode string) (Settings, error) {
|
||||
if !ValidRegistration(mode) {
|
||||
return Settings{}, fmt.Errorf("%w : mode d'inscription %q", ErrInvalidPath, mode)
|
||||
}
|
||||
return s.updateSettings(func(d *settingsDisk) { d.Registration = &mode })
|
||||
}
|
||||
|
||||
// WriteQuota règle le quota de l'espace personnel en Mo (0 : illimité).
|
||||
func (s *Store) WriteQuota(mb int64) (Settings, error) {
|
||||
if mb < 0 || mb > MaxQuotaMB {
|
||||
return Settings{}, fmt.Errorf("%w : quota invalide", ErrInvalidPath)
|
||||
}
|
||||
return s.updateSettings(func(d *settingsDisk) { d.QuotaMB = &mb })
|
||||
}
|
||||
|
||||
// WriteCommonReadonly règle l'accès en écriture à l'arborescence commune.
|
||||
func (s *Store) WriteCommonReadonly(ro bool) (Settings, error) {
|
||||
return s.updateSettings(func(d *settingsDisk) { d.CommonReadonly = &ro })
|
||||
}
|
||||
|
||||
// WriteTitle enregistre le titre affiché ("" = titre par défaut).
|
||||
func (s *Store) WriteTitle(title string) (Settings, error) {
|
||||
title = strings.TrimSpace(title)
|
||||
if !utf8.ValidString(title) || strings.ContainsAny(title, "\r\n\x00") {
|
||||
return Settings{}, fmt.Errorf("%w : titre", ErrInvalidPath)
|
||||
}
|
||||
if utf8.RuneCountInString(title) > MaxTitleLen {
|
||||
return Settings{}, fmt.Errorf("%w : titre de %d caractères max", ErrInvalidPath, MaxTitleLen)
|
||||
}
|
||||
return s.updateSettings(func(d *settingsDisk) { d.Title = title })
|
||||
}
|
||||
|
||||
// ReadLogo renvoie le logo PNG 64x64, ou ErrNotFound.
|
||||
func (s *Store) ReadLogo() ([]byte, error) {
|
||||
b, err := os.ReadFile(filepath.Join(s.root, logoFile))
|
||||
return b, mapErr(err)
|
||||
}
|
||||
|
||||
// WriteLogo décode un PNG, le recadre au centre en carré, le ramène à
|
||||
// LogoSize x LogoSize et l'enregistre (ré-encodé : aucune donnée annexe du
|
||||
// fichier d'origine n'est conservée).
|
||||
func (s *Store) WriteLogo(data []byte) (Settings, error) {
|
||||
cfg, err := png.DecodeConfig(bytes.NewReader(data))
|
||||
if err != nil {
|
||||
return Settings{}, fmt.Errorf("%w : PNG attendu", ErrInvalidImage)
|
||||
}
|
||||
if cfg.Width < 1 || cfg.Height < 1 || cfg.Width > maxLogoSide || cfg.Height > maxLogoSide {
|
||||
return Settings{}, fmt.Errorf("%w : %dx%d px max", ErrInvalidImage, maxLogoSide, maxLogoSide)
|
||||
}
|
||||
img, err := png.Decode(bytes.NewReader(data))
|
||||
if err != nil {
|
||||
return Settings{}, fmt.Errorf("%w : PNG illisible", ErrInvalidImage)
|
||||
}
|
||||
var buf bytes.Buffer
|
||||
if err := png.Encode(&buf, squareResize(img, LogoSize)); err != nil {
|
||||
return Settings{}, err
|
||||
}
|
||||
if err := atomicWrite(filepath.Join(s.root, logoFile), buf.Bytes()); err != nil {
|
||||
return Settings{}, err
|
||||
}
|
||||
return s.ReadSettings()
|
||||
}
|
||||
|
||||
// DeleteLogo supprime le logo (sans erreur s'il est absent).
|
||||
func (s *Store) DeleteLogo() (Settings, error) {
|
||||
if err := os.Remove(filepath.Join(s.root, logoFile)); err != nil && !errors.Is(err, fs.ErrNotExist) {
|
||||
return Settings{}, err
|
||||
}
|
||||
return s.ReadSettings()
|
||||
}
|
||||
|
||||
// squareResize recadre img au centre (carré) puis le rééchantillonne en n x n
|
||||
// par moyenne de surface (filtre « boîte » pondéré), en alpha prémultiplié
|
||||
// pour éviter les franges sombres sur les bords transparents.
|
||||
func squareResize(img image.Image, n int) *image.RGBA {
|
||||
b := img.Bounds()
|
||||
side := min(b.Dx(), b.Dy())
|
||||
crop := image.Rect(0, 0, side, side).Add(b.Min).
|
||||
Add(image.Pt((b.Dx()-side)/2, (b.Dy()-side)/2))
|
||||
src := image.NewRGBA(image.Rect(0, 0, side, side))
|
||||
draw.Draw(src, src.Bounds(), img, crop.Min, draw.Src)
|
||||
|
||||
w := boxWeights(side, n)
|
||||
dst := image.NewRGBA(image.Rect(0, 0, n, n))
|
||||
for dy := 0; dy < n; dy++ {
|
||||
for dx := 0; dx < n; dx++ {
|
||||
var acc [4]float64
|
||||
var total float64
|
||||
for _, wy := range w[dy] {
|
||||
row := wy.i * src.Stride
|
||||
for _, wx := range w[dx] {
|
||||
k := wy.w * wx.w
|
||||
p := src.Pix[row+wx.i*4:]
|
||||
for c := range acc {
|
||||
acc[c] += k * float64(p[c])
|
||||
}
|
||||
total += k
|
||||
}
|
||||
}
|
||||
o := dst.PixOffset(dx, dy)
|
||||
for c := range acc {
|
||||
dst.Pix[o+c] = uint8(acc[c]/total + 0.5)
|
||||
}
|
||||
}
|
||||
}
|
||||
return dst
|
||||
}
|
||||
|
||||
type weight struct {
|
||||
i int
|
||||
w float64
|
||||
}
|
||||
|
||||
// boxWeights calcule, pour chaque pixel cible, les pixels source qu'il couvre
|
||||
// et la fraction couverte. Fonctionne aussi en agrandissement (côté < n).
|
||||
func boxWeights(side, n int) [][]weight {
|
||||
scale := float64(side) / float64(n)
|
||||
out := make([][]weight, n)
|
||||
for d := range out {
|
||||
lo, hi := float64(d)*scale, float64(d+1)*scale
|
||||
for i := int(lo); i < side && float64(i) < hi; i++ {
|
||||
w := min(hi, float64(i+1)) - max(lo, float64(i))
|
||||
if w > 0 {
|
||||
out[d] = append(out[d], weight{i, w})
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,428 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"crypto/hmac"
|
||||
"crypto/pbkdf2"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Partage en lecture seule : un lien /s/<jeton> donne accès à un fichier ou à
|
||||
// un dossier (navigation et téléchargement) sans authentification, avec un mot
|
||||
// de passe facultatif. Le jeton est <id>.<signature> : id aléatoire (128 bits)
|
||||
// et HMAC-SHA256 de l'id par la clé du serveur. Un lien est valide si sa
|
||||
// signature est correcte, si son id figure dans .shares.json (révocation
|
||||
// lien par lien) et s'il n'a pas expiré. Changer de clé (RevokeAllShares)
|
||||
// invalide tous les liens d'un coup.
|
||||
//
|
||||
// Clé : SHARE_SECRET si défini, sinon .share-secret (générée au premier
|
||||
// partage, 0600). Le lien suit l'élément s'il est renommé ou déplacé et
|
||||
// disparaît s'il est supprimé.
|
||||
|
||||
const (
|
||||
sharesFile = ".shares.json"
|
||||
secretFile = ".share-secret"
|
||||
shareIDLen = 16 // octets aléatoires
|
||||
shareSigLen = 16 // octets de HMAC conservés
|
||||
)
|
||||
|
||||
// Share décrit un lien de partage.
|
||||
type Share struct {
|
||||
ID string `json:"id"`
|
||||
Token string `json:"token"`
|
||||
Path string `json:"path"`
|
||||
IsDir bool `json:"isDir"`
|
||||
Created time.Time `json:"created"`
|
||||
Expires *time.Time `json:"expires,omitempty"`
|
||||
Protected bool `json:"protected,omitempty"` // protégé par un mot de passe
|
||||
Downloads int `json:"downloads,omitempty"` // téléchargements depuis le lien
|
||||
|
||||
pw string // empreinte du mot de passe (jamais exposée)
|
||||
}
|
||||
|
||||
// ShareOptions règle un nouveau lien : durée de validité (0 : sans expiration)
|
||||
// et mot de passe facultatif.
|
||||
type ShareOptions struct {
|
||||
TTL time.Duration
|
||||
Password string
|
||||
}
|
||||
|
||||
type shareDisk struct {
|
||||
Path string `json:"path"`
|
||||
Created time.Time `json:"created"`
|
||||
Expires *time.Time `json:"expires,omitempty"`
|
||||
Password string `json:"pw,omitempty"`
|
||||
Downloads int `json:"downloads,omitempty"`
|
||||
}
|
||||
|
||||
var b64 = base64.RawURLEncoding
|
||||
|
||||
// SetShareSecret impose la clé de signature (variable SHARE_SECRET).
|
||||
func (s *Store) SetShareSecret(secret string) {
|
||||
s.sharesMu.Lock()
|
||||
defer s.sharesMu.Unlock()
|
||||
s.shareKey = []byte(secret)
|
||||
s.fixedKey = true
|
||||
}
|
||||
|
||||
// key renvoie la clé de signature, créée au besoin ; appelé sous sharesMu.
|
||||
func (s *Store) key() ([]byte, error) {
|
||||
if s.keyFrom != nil {
|
||||
return s.keyFrom.lockedKey()
|
||||
}
|
||||
if s.shareKey != nil {
|
||||
return s.shareKey, nil
|
||||
}
|
||||
p := filepath.Join(s.root, secretFile)
|
||||
b, err := os.ReadFile(p)
|
||||
if err == nil {
|
||||
if k, err := hex.DecodeString(strings.TrimSpace(string(b))); err == nil && len(k) >= 32 {
|
||||
s.shareKey = k
|
||||
return k, nil
|
||||
}
|
||||
} else if !errors.Is(err, fs.ErrNotExist) {
|
||||
return nil, err
|
||||
}
|
||||
return s.newKey()
|
||||
}
|
||||
|
||||
// lockedKey renvoie la clé de signature pour un espace personnel.
|
||||
func (s *Store) lockedKey() ([]byte, error) {
|
||||
s.sharesMu.Lock()
|
||||
defer s.sharesMu.Unlock()
|
||||
return s.key()
|
||||
}
|
||||
|
||||
func (s *Store) newKey() ([]byte, error) {
|
||||
k := make([]byte, 32)
|
||||
if _, err := rand.Read(k); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
p := filepath.Join(s.root, secretFile)
|
||||
if err := atomicWrite(p, []byte(hex.EncodeToString(k)+"\n")); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_ = os.Chmod(p, 0o600)
|
||||
s.shareKey = k
|
||||
return k, nil
|
||||
}
|
||||
|
||||
func sign(key []byte, id string) string {
|
||||
m := hmac.New(sha256.New, key)
|
||||
m.Write([]byte("upandown-share:" + id))
|
||||
return b64.EncodeToString(m.Sum(nil)[:shareSigLen])
|
||||
}
|
||||
|
||||
func (s *Store) readShares() (map[string]shareDisk, error) {
|
||||
out := map[string]shareDisk{}
|
||||
b, err := os.ReadFile(filepath.Join(s.root, sharesFile))
|
||||
switch {
|
||||
case errors.Is(err, fs.ErrNotExist):
|
||||
return out, nil
|
||||
case err != nil:
|
||||
return nil, err
|
||||
}
|
||||
var d struct {
|
||||
Links map[string]shareDisk `json:"links"`
|
||||
}
|
||||
if err := json.Unmarshal(b, &d); err != nil {
|
||||
return nil, fmt.Errorf("%s : %w", sharesFile, err)
|
||||
}
|
||||
if d.Links != nil {
|
||||
out = d.Links
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (s *Store) writeShares(m map[string]shareDisk) error {
|
||||
b, err := json.Marshal(map[string]any{"links": m})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
p := filepath.Join(s.root, sharesFile)
|
||||
if err := atomicWrite(p, b); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Chmod(p, 0o600)
|
||||
}
|
||||
|
||||
// editShares applique edit à la liste des liens sous verrou ; edit renvoie
|
||||
// false si rien n'a changé (pas d'écriture).
|
||||
func (s *Store) editShares(edit func(map[string]shareDisk) (bool, error)) error {
|
||||
s.sharesMu.Lock()
|
||||
defer s.sharesMu.Unlock()
|
||||
m, err := s.readShares()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
changed, err := edit(m)
|
||||
if err != nil || !changed {
|
||||
return err
|
||||
}
|
||||
return s.writeShares(m)
|
||||
}
|
||||
|
||||
func (s *Store) toShare(key []byte, id string, d shareDisk) Share {
|
||||
sh := Share{ID: id, Token: id + "." + sign(key, id), Path: d.Path, Created: d.Created, Expires: d.Expires,
|
||||
Protected: d.Password != "", Downloads: d.Downloads, pw: d.Password}
|
||||
if fi, err := os.Stat(absOf(s, d.Path)); err == nil {
|
||||
sh.IsDir = fi.IsDir()
|
||||
}
|
||||
return sh
|
||||
}
|
||||
|
||||
// MaxPasswordLen borne le mot de passe d'un lien de partage.
|
||||
const MaxPasswordLen = 200
|
||||
|
||||
// CreateShare crée un lien de partage d'un fichier ou d'un dossier.
|
||||
func (s *Store) CreateShare(rel string, o ShareOptions) (Share, error) {
|
||||
c, abs, err := s.resolve(rel)
|
||||
if err != nil {
|
||||
return Share{}, err
|
||||
}
|
||||
if c == "" {
|
||||
return Share{}, ErrInvalidPath
|
||||
}
|
||||
if fi, err := os.Lstat(abs); err != nil {
|
||||
return Share{}, mapErr(err)
|
||||
} else if !fi.IsDir() && !fi.Mode().IsRegular() {
|
||||
return Share{}, ErrNotFound
|
||||
}
|
||||
if o.TTL < 0 || len(o.Password) > MaxPasswordLen {
|
||||
return Share{}, fmt.Errorf("%w : durée ou mot de passe", ErrInvalidPath)
|
||||
}
|
||||
raw := make([]byte, shareIDLen)
|
||||
if _, err := rand.Read(raw); err != nil {
|
||||
return Share{}, err
|
||||
}
|
||||
id := b64.EncodeToString(raw)
|
||||
d := shareDisk{Path: c, Created: time.Now().UTC().Truncate(time.Second)}
|
||||
if o.TTL > 0 {
|
||||
e := d.Created.Add(o.TTL)
|
||||
d.Expires = &e
|
||||
}
|
||||
if o.Password != "" {
|
||||
d.Password = HashSharePassword(o.Password)
|
||||
}
|
||||
var out Share
|
||||
err = s.editShares(func(m map[string]shareDisk) (bool, error) {
|
||||
key, err := s.key()
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
m[id] = d
|
||||
out = s.toShare(key, id, d)
|
||||
return true, nil
|
||||
})
|
||||
return out, err
|
||||
}
|
||||
|
||||
// Shares liste les liens (d'un schéma, ou tous si rel est vide), les plus
|
||||
// récents en premier. Les liens expirés sont purgés au passage.
|
||||
func (s *Store) Shares(rel string) ([]Share, error) {
|
||||
c := ""
|
||||
if rel != "" {
|
||||
var err error
|
||||
if c, _, err = s.resolve(rel); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
out := []Share{}
|
||||
err := s.editShares(func(m map[string]shareDisk) (bool, error) {
|
||||
key, err := s.key()
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
purged := false
|
||||
for id, d := range m {
|
||||
if d.Expires != nil && time.Now().After(*d.Expires) {
|
||||
delete(m, id)
|
||||
purged = true
|
||||
} else if c == "" || d.Path == c {
|
||||
out = append(out, s.toShare(key, id, d))
|
||||
}
|
||||
}
|
||||
return purged, nil
|
||||
})
|
||||
sort.Slice(out, func(i, j int) bool { return out[i].Created.After(out[j].Created) })
|
||||
return out, err
|
||||
}
|
||||
|
||||
// RevokeShare supprime un lien.
|
||||
func (s *Store) RevokeShare(id string) error {
|
||||
return s.editShares(func(m map[string]shareDisk) (bool, error) {
|
||||
if _, ok := m[id]; !ok {
|
||||
return false, ErrNotFound
|
||||
}
|
||||
delete(m, id)
|
||||
return true, nil
|
||||
})
|
||||
}
|
||||
|
||||
// RevokeAllShares supprime tous les liens et change la clé de signature
|
||||
// (sauf si elle est imposée par SHARE_SECRET ou reprise du Store principal).
|
||||
func (s *Store) RevokeAllShares() error {
|
||||
return s.editShares(func(m map[string]shareDisk) (bool, error) {
|
||||
clear(m)
|
||||
if !s.fixedKey && s.keyFrom == nil {
|
||||
if _, err := s.newKey(); err != nil {
|
||||
return false, err
|
||||
}
|
||||
}
|
||||
return true, nil
|
||||
})
|
||||
}
|
||||
|
||||
// ResolveShare vérifie un jeton et renvoie le lien. Toute anomalie (jeton
|
||||
// mal formé, signature fausse, lien révoqué ou expiré) donne ErrNotFound.
|
||||
func (s *Store) ResolveShare(token string) (Share, error) {
|
||||
id, sig, ok := strings.Cut(token, ".")
|
||||
if !ok || len(id) != b64.EncodedLen(shareIDLen) || len(sig) != b64.EncodedLen(shareSigLen) {
|
||||
return Share{}, ErrNotFound
|
||||
}
|
||||
s.sharesMu.Lock()
|
||||
defer s.sharesMu.Unlock()
|
||||
key, err := s.key()
|
||||
if err != nil {
|
||||
return Share{}, err
|
||||
}
|
||||
if subtle.ConstantTimeCompare([]byte(sig), []byte(sign(key, id))) != 1 {
|
||||
return Share{}, ErrNotFound
|
||||
}
|
||||
m, err := s.readShares()
|
||||
if err != nil {
|
||||
return Share{}, err
|
||||
}
|
||||
d, ok := m[id]
|
||||
if !ok || (d.Expires != nil && time.Now().After(*d.Expires)) {
|
||||
return Share{}, ErrNotFound
|
||||
}
|
||||
return s.toShare(key, id, d), nil
|
||||
}
|
||||
|
||||
// CheckPassword vérifie le mot de passe d'un lien protégé.
|
||||
func (sh Share) CheckPassword(pw string) bool {
|
||||
return sh.pw != "" && CheckSharePassword(sh.pw, pw)
|
||||
}
|
||||
|
||||
// UnlockCookie renvoie la valeur du cookie qui prouve que le mot de passe du
|
||||
// lien a été saisi : HMAC de l'id et de l'empreinte du mot de passe.
|
||||
func (s *Store) UnlockCookie(sh Share) (string, error) {
|
||||
s.sharesMu.Lock()
|
||||
defer s.sharesMu.Unlock()
|
||||
key, err := s.key()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
m := hmac.New(sha256.New, key)
|
||||
m.Write([]byte("upandown-unlock:" + sh.ID + ":" + sh.pw))
|
||||
return b64.EncodeToString(m.Sum(nil)), nil
|
||||
}
|
||||
|
||||
// CountDownload incrémente le compteur de téléchargements d'un lien.
|
||||
func (s *Store) CountDownload(id string) {
|
||||
_ = s.editShares(func(m map[string]shareDisk) (bool, error) {
|
||||
d, ok := m[id]
|
||||
if !ok {
|
||||
return false, nil
|
||||
}
|
||||
d.Downloads++
|
||||
m[id] = d
|
||||
return true, nil
|
||||
})
|
||||
}
|
||||
|
||||
// SharedPath joint le chemin partagé et un sous-chemin demandé par le visiteur
|
||||
// du lien (vide : l'élément partagé lui-même). Un lien vers un fichier n'accepte
|
||||
// pas de sous-chemin ; ".." et les noms cachés sont refusés.
|
||||
func SharedPath(sh Share, sub string) (string, error) {
|
||||
if sub == "" {
|
||||
return sh.Path, nil
|
||||
}
|
||||
if !sh.IsDir {
|
||||
return "", ErrNotFound
|
||||
}
|
||||
c, err := Clean(sub)
|
||||
if err != nil || c == "" {
|
||||
return "", ErrNotFound
|
||||
}
|
||||
return sh.Path + "/" + c, nil
|
||||
}
|
||||
|
||||
// Les opérations suivantes accompagnent Move/Delete.
|
||||
|
||||
func (s *Store) moveShares(from, to string) {
|
||||
_ = s.editShares(func(m map[string]shareDisk) (bool, error) {
|
||||
changed := false
|
||||
for id, d := range m {
|
||||
if under(d.Path, from) {
|
||||
d.Path = to + d.Path[len(from):]
|
||||
m[id] = d
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
return changed, nil
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Store) removeShares(c string) {
|
||||
_ = s.editShares(func(m map[string]shareDisk) (bool, error) {
|
||||
changed := false
|
||||
for id, d := range m {
|
||||
if under(d.Path, c) {
|
||||
delete(m, id)
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
return changed, nil
|
||||
})
|
||||
}
|
||||
|
||||
// --- Mots de passe de liens -----------------------------------------------------------
|
||||
|
||||
const sharePwIter = 100_000
|
||||
|
||||
// HashSharePassword dérive une empreinte PBKDF2-SHA256 « iter$sel$hash ».
|
||||
func HashSharePassword(pw string) string {
|
||||
salt := make([]byte, 16)
|
||||
_, _ = rand.Read(salt)
|
||||
return derive(pw, salt, sharePwIter)
|
||||
}
|
||||
|
||||
func derive(pw string, salt []byte, iter int) string {
|
||||
h, err := pbkdf2.Key(sha256.New, pw, salt, iter, 32)
|
||||
if err != nil {
|
||||
panic(err) // paramètres constants valides
|
||||
}
|
||||
return fmt.Sprintf("%d$%s$%s", iter, b64.EncodeToString(salt), b64.EncodeToString(h))
|
||||
}
|
||||
|
||||
// CheckSharePassword compare un mot de passe à une empreinte HashSharePassword.
|
||||
func CheckSharePassword(hash, pw string) bool {
|
||||
parts := strings.Split(hash, "$")
|
||||
if len(parts) != 3 {
|
||||
return false
|
||||
}
|
||||
iter, err := strconv.Atoi(parts[0])
|
||||
if err != nil || iter < 1 || iter > 10_000_000 {
|
||||
return false
|
||||
}
|
||||
salt, err := b64.DecodeString(parts[1])
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return subtle.ConstantTimeCompare([]byte(derive(pw, salt, iter)), []byte(hash)) == 1
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,290 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func newSpaces(t *testing.T) *Spaces {
|
||||
t.Helper()
|
||||
return NewSpaces(newStore(t))
|
||||
}
|
||||
|
||||
func space(t *testing.T, sp *Spaces, id string, admin bool) *Space {
|
||||
t.Helper()
|
||||
u, err := sp.For(id, admin)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return u
|
||||
}
|
||||
|
||||
func uput(t *testing.T, u *Space, p, content string) Entry {
|
||||
t.Helper()
|
||||
e, err := u.Put(p, strings.NewReader(content), int64(len(content)), PutOptions{})
|
||||
if err != nil {
|
||||
t.Fatalf("Put(%s) : %v", p, err)
|
||||
}
|
||||
return e
|
||||
}
|
||||
|
||||
func TestPersonalSpaceIsPrivate(t *testing.T) {
|
||||
sp := newSpaces(t)
|
||||
alice, bob := space(t, sp, "alice", false), space(t, sp, "bob", false)
|
||||
uput(t, alice, ".perso/secret.txt", "S")
|
||||
uput(t, alice, "commun.txt", "C")
|
||||
if es, _ := bob.List(".perso"); len(es) != 0 {
|
||||
t.Errorf("bob voit l'espace d'alice : %v", es)
|
||||
}
|
||||
if es, _ := alice.List(".perso"); len(es) != 1 || es[0].Path != ".perso/secret.txt" {
|
||||
t.Errorf("alice : %v", es)
|
||||
}
|
||||
root, _ := bob.List("")
|
||||
var specials []string
|
||||
for _, e := range root {
|
||||
if e.Special != "" {
|
||||
specials = append(specials, e.Special)
|
||||
}
|
||||
}
|
||||
if len(specials) != 3 {
|
||||
t.Errorf("dossiers virtuels = %v", specials)
|
||||
}
|
||||
if hits, _ := bob.Search("secret", Filter{}, 10); len(hits) != 0 {
|
||||
t.Errorf("recherche : %v", hits)
|
||||
}
|
||||
// Chemins qui tentent d'atteindre les espaces d'autrui.
|
||||
for _, p := range []string{".users/alice/home/secret.txt", "../.users/alice/home/secret.txt"} {
|
||||
if _, _, err := bob.Open(p); err == nil {
|
||||
t.Errorf("accès à %s", p)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMoveBetweenSpacesAndFavorites(t *testing.T) {
|
||||
sp := newSpaces(t)
|
||||
alice := space(t, sp, "alice", false)
|
||||
uput(t, alice, "doc.pdf", "PDF")
|
||||
if err := alice.EditTags([]string{"doc.pdf"}, []string{"important"}, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := alice.SetFavorite([]string{"doc.pdf"}, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
favs, _ := alice.List(".favoris")
|
||||
if len(favs) != 1 || favs[0].Path != "doc.pdf" || favs[0].Broken {
|
||||
t.Fatalf("favoris = %+v", favs)
|
||||
}
|
||||
// Déplacement commun -> personnel : le favori suit, les tags aussi.
|
||||
if _, err := alice.Move("doc.pdf", ".perso/doc.pdf"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
favs, _ = alice.List(".favoris")
|
||||
if len(favs) != 1 || favs[0].Path != ".perso/doc.pdf" || favs[0].Broken {
|
||||
t.Errorf("favori après déplacement = %+v", favs)
|
||||
}
|
||||
es, _ := alice.List(".perso")
|
||||
if len(es) != 1 || len(es[0].Tags) != 1 {
|
||||
t.Errorf("tags après déplacement : %+v", es)
|
||||
}
|
||||
// Un dossier peut être favori.
|
||||
if _, err := alice.Mkdir("projets"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := alice.SetFavorite([]string{"projets"}, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if favs, _ = alice.List(".favoris"); len(favs) != 2 {
|
||||
t.Errorf("favoris dossier : %+v", favs)
|
||||
}
|
||||
// Suppression de l'original : le favori disparaît.
|
||||
if err := alice.Delete(".perso/doc.pdf", false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if favs, _ = alice.List(".favoris"); len(favs) != 1 {
|
||||
t.Errorf("favori d'un fichier supprimé : %+v", favs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCommonReadonly(t *testing.T) {
|
||||
sp := newSpaces(t)
|
||||
admin, user := space(t, sp, "root", true), space(t, sp, "bob", false)
|
||||
uput(t, admin, "regles.txt", "R")
|
||||
if _, err := sp.Main.WriteCommonReadonly(true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := user.Put("x.txt", strings.NewReader("x"), 1, PutOptions{}); !errors.Is(err, ErrForbidden) {
|
||||
t.Errorf("écriture : %v", err)
|
||||
}
|
||||
if _, err := user.Mkdir("d"); !errors.Is(err, ErrForbidden) {
|
||||
t.Errorf("Mkdir : %v", err)
|
||||
}
|
||||
if err := user.Delete("regles.txt", false); !errors.Is(err, ErrForbidden) {
|
||||
t.Errorf("Delete : %v", err)
|
||||
}
|
||||
if _, err := user.Move("regles.txt", "r2.txt"); !errors.Is(err, ErrForbidden) {
|
||||
t.Errorf("Move : %v", err)
|
||||
}
|
||||
if err := user.EditTags([]string{"regles.txt"}, []string{"t"}, nil); !errors.Is(err, ErrForbidden) {
|
||||
t.Errorf("EditTags : %v", err)
|
||||
}
|
||||
if _, err := user.Copy("regles.txt", "copie.txt"); !errors.Is(err, ErrForbidden) {
|
||||
t.Errorf("Copy : %v", err)
|
||||
}
|
||||
// Lecture et espace personnel restent libres, copie vers le personnel aussi.
|
||||
if _, _, err := user.Open("regles.txt"); err != nil {
|
||||
t.Errorf("lecture : %v", err)
|
||||
}
|
||||
if _, err := user.Copy("regles.txt", ".perso/regles.txt"); err != nil {
|
||||
t.Errorf("copie vers le personnel : %v", err)
|
||||
}
|
||||
uput(t, user, ".perso/mien.txt", "M")
|
||||
// L'administrateur écrit toujours.
|
||||
uput(t, admin, "admin.txt", "A")
|
||||
}
|
||||
|
||||
func TestQuota(t *testing.T) {
|
||||
sp := newSpaces(t)
|
||||
if _, err := sp.Main.WriteQuota(1); err != nil { // 1 Mo
|
||||
t.Fatal(err)
|
||||
}
|
||||
u := space(t, sp, "alice", false)
|
||||
big := strings.Repeat("x", 700<<10)
|
||||
uput(t, u, ".perso/a.bin", big)
|
||||
if _, err := u.Put(".perso/b.bin", strings.NewReader(big), int64(len(big)), PutOptions{}); !errors.Is(err, ErrQuota) {
|
||||
t.Errorf("dépassement : %v", err)
|
||||
}
|
||||
// Sans taille annoncée : coupé en cours de route.
|
||||
if _, err := u.Put(".perso/c.bin", strings.NewReader(big), -1, PutOptions{}); !errors.Is(err, ErrQuota) {
|
||||
t.Errorf("dépassement en flux : %v", err)
|
||||
}
|
||||
if used, quota := u.Usage(); quota != 1<<20 || used < 700<<10 {
|
||||
t.Errorf("Usage = %d / %d", used, quota)
|
||||
}
|
||||
// Le quota ne concerne pas l'arborescence commune.
|
||||
uput(t, u, "commun.bin", big+big)
|
||||
// Déplacer vers le personnel doit tenir dans le quota.
|
||||
if _, err := u.Move("commun.bin", ".perso/commun.bin"); !errors.Is(err, ErrQuota) {
|
||||
t.Errorf("déplacement : %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMaxUpload(t *testing.T) {
|
||||
sp := newSpaces(t)
|
||||
sp.MaxUpload = 10
|
||||
u := space(t, sp, "alice", false)
|
||||
if _, err := u.Put("a.bin", strings.NewReader("12345678901"), 11, PutOptions{}); !errors.Is(err, ErrTooLarge) {
|
||||
t.Errorf("taille annoncée : %v", err)
|
||||
}
|
||||
if _, err := u.Put("b.bin", strings.NewReader("12345678901"), -1, PutOptions{}); !errors.Is(err, ErrTooLarge) {
|
||||
t.Errorf("flux : %v", err)
|
||||
}
|
||||
uput(t, u, "ok.bin", "1234567890")
|
||||
}
|
||||
|
||||
func TestShareInPersonalSpaceResolvedGlobally(t *testing.T) {
|
||||
sp := newSpaces(t)
|
||||
alice := space(t, sp, "alice", false)
|
||||
uput(t, alice, ".perso/p.txt", "P")
|
||||
sh, err := alice.CreateShare(".perso/p.txt", ShareOptions{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if sh.Path != ".perso/p.txt" {
|
||||
t.Errorf("chemin virtuel = %q", sh.Path)
|
||||
}
|
||||
got, st, err := sp.ResolveShare(sh.Token)
|
||||
if err != nil || got.Path != "p.txt" || st == sp.Main {
|
||||
t.Fatalf("ResolveShare = %+v, %v", got, err)
|
||||
}
|
||||
bob := space(t, sp, "bob", false)
|
||||
if l, _ := bob.Shares(""); len(l) != 0 {
|
||||
t.Errorf("bob voit les liens d'alice : %v", l)
|
||||
}
|
||||
if err := bob.RevokeShare(sh.ID); err == nil {
|
||||
t.Error("bob a révoqué le lien d'alice")
|
||||
}
|
||||
if err := alice.RevokeAllShares(); !errors.Is(err, ErrForbidden) {
|
||||
t.Errorf("révocation générale par un non-admin : %v", err)
|
||||
}
|
||||
if err := alice.RevokeShare(sh.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTrashSeenAcrossSpaces(t *testing.T) {
|
||||
sp := newSpaces(t)
|
||||
alice := space(t, sp, "alice", false)
|
||||
uput(t, alice, "c.txt", "C")
|
||||
uput(t, alice, ".perso/p.txt", "P")
|
||||
_ = alice.Delete("c.txt", false)
|
||||
_ = alice.Delete(".perso/p.txt", false)
|
||||
tr, _ := alice.Trash()
|
||||
if len(tr) != 2 {
|
||||
t.Fatalf("poubelle = %+v", tr)
|
||||
}
|
||||
res := alice.RestoreTrash([]string{tr[0].Path, tr[1].Path})
|
||||
for _, r := range res {
|
||||
if r.Error != "" {
|
||||
t.Errorf("restauration : %+v", r)
|
||||
}
|
||||
}
|
||||
if es, _ := alice.List(".perso"); len(es) != 1 {
|
||||
t.Errorf("perso : %v", es)
|
||||
}
|
||||
}
|
||||
|
||||
func TestZipItemsAcrossSpaces(t *testing.T) {
|
||||
sp := newSpaces(t)
|
||||
alice := space(t, sp, "alice", false)
|
||||
uput(t, alice, "notes.txt", "1")
|
||||
uput(t, alice, ".perso/notes.txt", "2")
|
||||
items, name, err := alice.ZipItems([]string{"notes.txt", ".perso/notes.txt"})
|
||||
if err != nil || len(items) != 2 || items[0].Name == items[1].Name || name != "fichiers" {
|
||||
t.Errorf("ZipItems = %+v, %q, %v", items, name, err)
|
||||
}
|
||||
if _, _, err := alice.ZipItems([]string{"../../etc/passwd"}); err == nil {
|
||||
t.Error("chemin hors racine accepté")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRetireUser(t *testing.T) {
|
||||
sp := newSpaces(t)
|
||||
alice := space(t, sp, "alice", false)
|
||||
uput(t, alice, ".perso/a.txt", "A")
|
||||
if err := sp.RetireUser("alice"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Un nouvel « alice » ne retrouve rien.
|
||||
again := space(t, sp, "alice", false)
|
||||
if es, _ := again.List(".perso"); len(es) != 0 {
|
||||
t.Errorf("héritage de fichiers : %v", es)
|
||||
}
|
||||
des, _ := os.ReadDir(filepath.Join(sp.Main.root, ".users-removed"))
|
||||
if len(des) != 1 {
|
||||
t.Errorf("espace non mis de côté : %v", des)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSettingsDefaultsAndOverride(t *testing.T) {
|
||||
s := newStore(t)
|
||||
s.Defaults = SettingsDefaults{Registration: RegApproval, QuotaMB: 50, CommonReadonly: true, TrashDays: 30}
|
||||
st, _ := s.ReadSettings()
|
||||
if st.Registration != RegApproval || st.QuotaMB != 50 || !st.CommonReadonly || st.TrashDays != 30 {
|
||||
t.Errorf("défauts = %+v", st)
|
||||
}
|
||||
if st, _ = s.WriteRegistration(RegOpen); st.Registration != RegOpen {
|
||||
t.Errorf("registration = %+v", st)
|
||||
}
|
||||
if st, _ = s.WriteQuota(0); st.QuotaMB != 0 { // 0 explicite : illimité, malgré le défaut
|
||||
t.Errorf("quota = %+v", st)
|
||||
}
|
||||
if _, err := s.WriteRegistration("n'importe quoi"); err == nil {
|
||||
t.Error("mode invalide accepté")
|
||||
}
|
||||
if _, err := s.WriteQuota(-1); err == nil {
|
||||
t.Error("quota négatif accepté")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,714 @@
|
||||
// Package storage gère l'arborescence de fichiers sur disque.
|
||||
//
|
||||
// Tous les chemins manipulés par l'API sont relatifs à la racine (DATA_DIR),
|
||||
// au format "slash" (a/b/rapport.pdf). Le package garantit qu'aucun chemin ne
|
||||
// sort de la racine, y compris via un lien symbolique, et que les fichiers
|
||||
// internes (noms commençant par un point : .trash, .history, .meta.json...)
|
||||
// ne sont jamais exposés.
|
||||
package storage
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
const (
|
||||
trashDir = ".trash"
|
||||
thumbsDir = ".thumbs"
|
||||
|
||||
// MaxNameLen borne la longueur d'un nom de fichier ou de dossier (octets).
|
||||
MaxNameLen = 255
|
||||
)
|
||||
|
||||
var (
|
||||
ErrNotFound = errors.New("introuvable")
|
||||
ErrExists = errors.New("existe déjà")
|
||||
ErrInvalidPath = errors.New("chemin invalide")
|
||||
ErrConflict = errors.New("le fichier a été modifié entre-temps")
|
||||
ErrNotEmpty = errors.New("dossier non vide")
|
||||
ErrForbidden = errors.New("action non autorisée")
|
||||
ErrQuota = errors.New("quota de stockage dépassé")
|
||||
ErrTooLarge = errors.New("fichier trop volumineux")
|
||||
)
|
||||
|
||||
// Entry décrit un élément de l'arborescence.
|
||||
type Entry struct {
|
||||
Name string `json:"name"`
|
||||
Path string `json:"path"`
|
||||
IsDir bool `json:"isDir"`
|
||||
Size int64 `json:"size"`
|
||||
ModTime time.Time `json:"modTime"`
|
||||
|
||||
Tags []string `json:"tags,omitempty"`
|
||||
Favorite bool `json:"favorite,omitempty"`
|
||||
Icon string `json:"icon,omitempty"` // dossier : icône choisie (meta.go)
|
||||
EditedBy string `json:"editedBy,omitempty"` // fichier : dernier utilisateur à l'avoir déposé
|
||||
|
||||
// Détails (details.go), seulement sur demande (/api/list?details=1).
|
||||
Details *Details `json:"details,omitempty"`
|
||||
|
||||
// Dossiers virtuels et favoris (spaces.go).
|
||||
Special string `json:"special,omitempty"` // "favoris", "perso" ou "poubelle" : entrée de la racine
|
||||
Link string `json:"link,omitempty"` // nom du lien dans le dossier Favoris
|
||||
Broken bool `json:"broken,omitempty"` // favori dont l'élément d'origine a disparu
|
||||
|
||||
// Poubelle (trash.go, spaces.go).
|
||||
Count int `json:"count,omitempty"` // entrée « poubelle » de la racine : nombre d'éléments
|
||||
Origin string `json:"origin,omitempty"` // élément de la poubelle : chemin d'origine
|
||||
By string `json:"by,omitempty"` // élément de la poubelle : supprimé par
|
||||
}
|
||||
|
||||
// Store est un dépôt de fichiers enraciné dans un répertoire.
|
||||
type Store struct {
|
||||
root string
|
||||
|
||||
// History règle l'historique des versions (DefaultHistory par défaut).
|
||||
History HistoryPolicy
|
||||
|
||||
// Defaults : valeurs des paramètres tant que l'administrateur ne les a pas
|
||||
// modifiés (variables d'environnement, voir settings.go).
|
||||
Defaults SettingsDefaults
|
||||
|
||||
settingsMu sync.Mutex // sérialise les lectures-modifications de .settings.json
|
||||
index textIndex // texte des fichiers pour la recherche (search.go)
|
||||
thumbSem chan struct{}
|
||||
|
||||
metaMu sync.Mutex // tags, favoris, auteurs (meta.go)
|
||||
meta map[string]itemMeta // nil : pas encore chargé
|
||||
|
||||
sharesMu sync.Mutex // liens de partage (share.go)
|
||||
shareKey []byte // clé HMAC ; nil : pas encore chargée
|
||||
fixedKey bool // clé imposée par SHARE_SECRET
|
||||
keyFrom *Store // espace personnel : clé de signature du Store principal
|
||||
|
||||
usageMu sync.Mutex
|
||||
usageAt time.Time
|
||||
usageSize int64
|
||||
}
|
||||
|
||||
// New crée le répertoire racine si besoin et renvoie un Store.
|
||||
func New(root string) (*Store, error) {
|
||||
abs, err := filepath.Abs(root)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := os.MkdirAll(abs, 0o755); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Résout un éventuel lien symbolique sur la racine elle-même pour que
|
||||
// les comparaisons de préfixe soient fiables.
|
||||
if abs, err = filepath.EvalSymlinks(abs); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Store{root: abs, History: DefaultHistory, Defaults: DefaultSettings, thumbSem: make(chan struct{}, 2)}, nil
|
||||
}
|
||||
|
||||
// Clean normalise un chemin relatif : "/a/../b/" -> "b", "" -> "".
|
||||
// Les composants cachés (".trash", ".git"...), les caractères de contrôle et
|
||||
// les noms trop longs sont refusés.
|
||||
func Clean(rel string) (string, error) {
|
||||
if strings.ContainsRune(rel, 0) || strings.Contains(rel, `\`) || !utf8.ValidString(rel) {
|
||||
return "", ErrInvalidPath
|
||||
}
|
||||
c := strings.TrimPrefix(path.Clean("/"+rel), "/")
|
||||
if c == "" {
|
||||
return "", nil
|
||||
}
|
||||
for _, part := range strings.Split(c, "/") {
|
||||
if strings.HasPrefix(part, ".") || len(part) > MaxNameLen || strings.TrimSpace(part) != part {
|
||||
return "", ErrInvalidPath
|
||||
}
|
||||
for _, r := range part {
|
||||
if r < 0x20 || r == 0x7f {
|
||||
return "", ErrInvalidPath
|
||||
}
|
||||
}
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// resolve convertit un chemin relatif en chemin absolu sous la racine et
|
||||
// vérifie que l'ancêtre existant le plus proche ne s'échappe pas via symlink
|
||||
// et ne mène pas à un répertoire interne.
|
||||
func (s *Store) resolve(rel string) (string, string, error) {
|
||||
c, err := Clean(rel)
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
abs := filepath.Join(s.root, filepath.FromSlash(c))
|
||||
probe := abs
|
||||
for {
|
||||
real, err := filepath.EvalSymlinks(probe)
|
||||
if err == nil {
|
||||
if real != s.root && !strings.HasPrefix(real, s.root+string(os.PathSeparator)) {
|
||||
return "", "", ErrInvalidPath
|
||||
}
|
||||
if real != s.root {
|
||||
inner, _ := filepath.Rel(s.root, real)
|
||||
for _, part := range strings.Split(filepath.ToSlash(inner), "/") {
|
||||
if strings.HasPrefix(part, ".") {
|
||||
return "", "", ErrInvalidPath
|
||||
}
|
||||
}
|
||||
}
|
||||
break
|
||||
}
|
||||
if !errors.Is(err, fs.ErrNotExist) {
|
||||
return "", "", err
|
||||
}
|
||||
parent := filepath.Dir(probe)
|
||||
if parent == probe {
|
||||
return "", "", ErrInvalidPath
|
||||
}
|
||||
probe = parent
|
||||
}
|
||||
return c, abs, nil
|
||||
}
|
||||
|
||||
func mapErr(err error) error {
|
||||
switch {
|
||||
case err == nil:
|
||||
return nil
|
||||
case errors.Is(err, fs.ErrNotExist):
|
||||
return ErrNotFound
|
||||
case errors.Is(err, fs.ErrExist):
|
||||
return ErrExists
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func toEntry(rel string, fi fs.FileInfo) Entry {
|
||||
e := Entry{
|
||||
Name: fi.Name(),
|
||||
Path: rel,
|
||||
IsDir: fi.IsDir(),
|
||||
Size: fi.Size(),
|
||||
ModTime: fi.ModTime().UTC(),
|
||||
}
|
||||
if e.IsDir {
|
||||
e.Size = 0
|
||||
}
|
||||
return e
|
||||
}
|
||||
|
||||
func visible(name string) bool { return !strings.HasPrefix(name, ".") }
|
||||
|
||||
// List renvoie le contenu d'un dossier : dossiers d'abord, puis fichiers,
|
||||
// triés par nom (insensible à la casse).
|
||||
func (s *Store) List(rel string) ([]Entry, error) {
|
||||
c, abs, err := s.resolve(rel)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
des, err := os.ReadDir(abs)
|
||||
if err != nil {
|
||||
if errors.Is(err, fs.ErrNotExist) || strings.Contains(err.Error(), "not a directory") {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, mapErr(err)
|
||||
}
|
||||
out := make([]Entry, 0, len(des))
|
||||
meta := s.metaSnapshot()
|
||||
for _, de := range des {
|
||||
if !visible(de.Name()) || de.Type()&fs.ModeSymlink != 0 {
|
||||
continue
|
||||
}
|
||||
fi, err := de.Info()
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if !fi.IsDir() && !fi.Mode().IsRegular() {
|
||||
continue
|
||||
}
|
||||
e := toEntry(path.Join(c, de.Name()), fi)
|
||||
decorate(&e, meta)
|
||||
out = append(out, e)
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool {
|
||||
if out[i].IsDir != out[j].IsDir {
|
||||
return out[i].IsDir
|
||||
}
|
||||
return strings.ToLower(out[i].Name) < strings.ToLower(out[j].Name)
|
||||
})
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// Stat décrit un fichier ou un dossier.
|
||||
func (s *Store) Stat(rel string) (Entry, error) {
|
||||
c, abs, err := s.resolve(rel)
|
||||
if err != nil {
|
||||
return Entry{}, err
|
||||
}
|
||||
fi, err := os.Lstat(abs)
|
||||
if err != nil {
|
||||
return Entry{}, mapErr(err)
|
||||
}
|
||||
if fi.Mode()&fs.ModeSymlink != 0 {
|
||||
return Entry{}, ErrNotFound
|
||||
}
|
||||
e := toEntry(c, fi)
|
||||
decorate(&e, s.metaSnapshot())
|
||||
return e, nil
|
||||
}
|
||||
|
||||
// ETag calcule l'empreinte faible d'un fichier (taille et date de modification).
|
||||
func ETag(fi fs.FileInfo) string {
|
||||
return `W/"` + strconv.FormatInt(fi.Size(), 36) + "-" + strconv.FormatInt(fi.ModTime().UnixNano(), 36) + `"`
|
||||
}
|
||||
|
||||
// Open ouvre un fichier en lecture. Les liens symboliques sont refusés.
|
||||
func (s *Store) Open(rel string) (*os.File, fs.FileInfo, error) {
|
||||
c, abs, err := s.resolve(rel)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if c == "" {
|
||||
return nil, nil, ErrInvalidPath
|
||||
}
|
||||
fi, err := os.Lstat(abs)
|
||||
if err != nil {
|
||||
return nil, nil, mapErr(err)
|
||||
}
|
||||
if !fi.Mode().IsRegular() {
|
||||
return nil, nil, ErrNotFound
|
||||
}
|
||||
f, err := os.Open(abs)
|
||||
if err != nil {
|
||||
return nil, nil, mapErr(err)
|
||||
}
|
||||
if fi, err = f.Stat(); err != nil {
|
||||
f.Close()
|
||||
return nil, nil, err
|
||||
}
|
||||
return f, fi, nil
|
||||
}
|
||||
|
||||
// PutOptions règle l'écriture d'un fichier (Put).
|
||||
type PutOptions struct {
|
||||
// Conflict : conduite si le fichier existe. "" ou "fail" : ErrExists ;
|
||||
// "overwrite" : remplacement (la version précédente part dans l'historique) ;
|
||||
// "rename" : le nouveau fichier prend un nom libre « nom (2).ext ».
|
||||
Conflict string
|
||||
// IfMatch : ETag attendu du fichier remplacé (ErrConflict sinon) ; vide : pas de contrôle.
|
||||
IfMatch string
|
||||
// Limit : nombre maximal d'octets acceptés (0 : illimité) ; LimitErr est
|
||||
// renvoyée s'il est dépassé (ErrTooLarge ou ErrQuota).
|
||||
Limit int64
|
||||
LimitErr error
|
||||
// ModTime : date de modification à donner au fichier (zéro : maintenant).
|
||||
ModTime time.Time
|
||||
// By : utilisateur qui dépose le fichier (auteur et dernier auteur).
|
||||
By string
|
||||
}
|
||||
|
||||
// Put écrit un fichier de façon atomique et en flux (fichier temporaire dans
|
||||
// le dossier cible, fsync, rename) : un envoi interrompu ne laisse rien. Les
|
||||
// dossiers parents sont créés. Renvoie l'entrée écrite (son chemin peut
|
||||
// différer de rel avec Conflict = "rename").
|
||||
func (s *Store) Put(rel string, r io.Reader, o PutOptions) (Entry, error) {
|
||||
c, abs, err := s.resolve(rel)
|
||||
if err != nil {
|
||||
return Entry{}, err
|
||||
}
|
||||
if c == "" {
|
||||
return Entry{}, ErrInvalidPath
|
||||
}
|
||||
fi, err := os.Lstat(abs)
|
||||
exists := err == nil
|
||||
if err != nil && !errors.Is(err, fs.ErrNotExist) {
|
||||
return Entry{}, mapErr(err)
|
||||
}
|
||||
if exists {
|
||||
if fi.IsDir() {
|
||||
return Entry{}, fmt.Errorf("%w : un dossier porte déjà ce nom", ErrExists)
|
||||
}
|
||||
switch o.Conflict {
|
||||
case "overwrite":
|
||||
if o.IfMatch != "" && o.IfMatch != "*" && o.IfMatch != ETag(fi) {
|
||||
return Entry{}, ErrConflict
|
||||
}
|
||||
case "rename":
|
||||
c = s.freeName(c, false, " (%d)")
|
||||
if _, abs, err = s.resolve(c); err != nil {
|
||||
return Entry{}, err
|
||||
}
|
||||
exists = false
|
||||
default:
|
||||
return Entry{}, ErrExists
|
||||
}
|
||||
} else if o.IfMatch != "" && o.IfMatch != "*" {
|
||||
return Entry{}, ErrConflict
|
||||
}
|
||||
// Un composant du chemin ne doit pas être un fichier.
|
||||
if err := os.MkdirAll(filepath.Dir(abs), 0o755); err != nil {
|
||||
if errors.Is(err, fs.ErrExist) || strings.Contains(err.Error(), "not a directory") {
|
||||
return Entry{}, fmt.Errorf("%w : un fichier porte le nom d'un dossier du chemin", ErrExists)
|
||||
}
|
||||
return Entry{}, err
|
||||
}
|
||||
tmp, err := os.CreateTemp(filepath.Dir(abs), ".tmp-*")
|
||||
if err != nil {
|
||||
return Entry{}, err
|
||||
}
|
||||
defer os.Remove(tmp.Name()) // no-op après un rename réussi
|
||||
src := r
|
||||
if o.Limit > 0 {
|
||||
src = io.LimitReader(r, o.Limit+1)
|
||||
}
|
||||
n, err := io.Copy(tmp, src)
|
||||
if err != nil {
|
||||
tmp.Close()
|
||||
return Entry{}, err
|
||||
}
|
||||
if o.Limit > 0 && n > o.Limit {
|
||||
tmp.Close()
|
||||
if o.LimitErr != nil {
|
||||
return Entry{}, o.LimitErr
|
||||
}
|
||||
return Entry{}, ErrTooLarge
|
||||
}
|
||||
if err := tmp.Sync(); err != nil {
|
||||
tmp.Close()
|
||||
return Entry{}, err
|
||||
}
|
||||
if err := tmp.Close(); err != nil {
|
||||
return Entry{}, err
|
||||
}
|
||||
if err := os.Chmod(tmp.Name(), 0o644); err != nil {
|
||||
return Entry{}, err
|
||||
}
|
||||
if m := o.ModTime; !m.IsZero() && m.After(time.Date(1980, 1, 1, 0, 0, 0, 0, time.UTC)) && m.Before(time.Now().Add(24*time.Hour)) {
|
||||
_ = os.Chtimes(tmp.Name(), m, m)
|
||||
}
|
||||
if exists {
|
||||
s.autoSnapshot(c, abs, fi)
|
||||
}
|
||||
if err := os.Rename(tmp.Name(), abs); err != nil {
|
||||
return Entry{}, err
|
||||
}
|
||||
s.usageDirty()
|
||||
s.removeThumb(c)
|
||||
s.noteEdit(c, o.By, !exists)
|
||||
nfi, err := os.Stat(abs)
|
||||
if err != nil {
|
||||
return Entry{}, err
|
||||
}
|
||||
e := toEntry(c, nfi)
|
||||
e.EditedBy = o.By
|
||||
return e, nil
|
||||
}
|
||||
|
||||
// Mkdir crée un dossier (et ses parents).
|
||||
func (s *Store) Mkdir(rel string) (Entry, error) {
|
||||
c, abs, err := s.resolve(rel)
|
||||
if err != nil {
|
||||
return Entry{}, err
|
||||
}
|
||||
if c == "" {
|
||||
return Entry{}, ErrInvalidPath
|
||||
}
|
||||
if _, err := os.Lstat(abs); err == nil {
|
||||
return Entry{}, ErrExists
|
||||
}
|
||||
if err := os.MkdirAll(abs, 0o755); err != nil {
|
||||
if strings.Contains(err.Error(), "not a directory") {
|
||||
return Entry{}, fmt.Errorf("%w : un fichier porte le nom d'un dossier du chemin", ErrExists)
|
||||
}
|
||||
return Entry{}, mapErr(err)
|
||||
}
|
||||
fi, err := os.Stat(abs)
|
||||
if err != nil {
|
||||
return Entry{}, err
|
||||
}
|
||||
return toEntry(c, fi), nil
|
||||
}
|
||||
|
||||
// Move renomme ou déplace un fichier ou un dossier. La destination ne doit
|
||||
// pas exister ; un dossier ne peut pas être déplacé dans lui-même.
|
||||
func (s *Store) Move(from, to string) (Entry, error) {
|
||||
cf, af, err := s.resolve(from)
|
||||
if err != nil {
|
||||
return Entry{}, err
|
||||
}
|
||||
ct, at, err := s.resolve(to)
|
||||
if err != nil {
|
||||
return Entry{}, err
|
||||
}
|
||||
if cf == "" || ct == "" {
|
||||
return Entry{}, ErrInvalidPath
|
||||
}
|
||||
fi, err := os.Lstat(af)
|
||||
if err != nil {
|
||||
return Entry{}, mapErr(err)
|
||||
}
|
||||
if fi.IsDir() && (ct == cf || strings.HasPrefix(ct, cf+"/")) {
|
||||
return Entry{}, fmt.Errorf("%w : déplacement d'un dossier dans lui-même", ErrInvalidPath)
|
||||
}
|
||||
if _, err := os.Lstat(at); err == nil {
|
||||
// Renommage qui ne change que la casse (volume insensible à la casse).
|
||||
if !strings.EqualFold(cf, ct) || cf == ct {
|
||||
return Entry{}, ErrExists
|
||||
}
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(at), 0o755); err != nil {
|
||||
return Entry{}, err
|
||||
}
|
||||
if err := os.Rename(af, at); err != nil {
|
||||
return Entry{}, mapErr(err)
|
||||
}
|
||||
s.moveThumb(cf, ct, fi.IsDir())
|
||||
s.moveHistory(cf, ct)
|
||||
s.moveMeta(cf, ct)
|
||||
s.moveShares(cf, ct)
|
||||
fi, err = os.Stat(at)
|
||||
if err != nil {
|
||||
return Entry{}, err
|
||||
}
|
||||
e := toEntry(ct, fi)
|
||||
decorate(&e, s.metaSnapshot())
|
||||
return e, nil
|
||||
}
|
||||
|
||||
// MoveResult est le résultat d'un déplacement unitaire dans MoveMany.
|
||||
type MoveResult struct {
|
||||
From string `json:"from"`
|
||||
To string `json:"to,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
err error
|
||||
}
|
||||
|
||||
// Err renvoie l'erreur du déplacement (nil si réussi).
|
||||
func (r MoveResult) Err() error { return r.err }
|
||||
|
||||
// Copy duplique un fichier, ou un dossier avec tout son contenu (fichiers
|
||||
// réguliers seulement). Les tags sont copiés, pas les favoris ni les partages.
|
||||
func (s *Store) Copy(from, to string) (Entry, error) {
|
||||
cf, af, err := s.resolve(from)
|
||||
if err != nil {
|
||||
return Entry{}, err
|
||||
}
|
||||
ct, at, err := s.resolve(to)
|
||||
if err != nil {
|
||||
return Entry{}, err
|
||||
}
|
||||
if cf == "" || ct == "" {
|
||||
return Entry{}, ErrInvalidPath
|
||||
}
|
||||
fi, err := os.Lstat(af)
|
||||
if err != nil {
|
||||
return Entry{}, mapErr(err)
|
||||
}
|
||||
if _, err := os.Lstat(at); err == nil {
|
||||
return Entry{}, ErrExists
|
||||
}
|
||||
if fi.IsDir() {
|
||||
if ct == cf || strings.HasPrefix(ct, cf+"/") {
|
||||
return Entry{}, fmt.Errorf("%w : copie d'un dossier dans lui-même", ErrInvalidPath)
|
||||
}
|
||||
err = copyTree(af, at)
|
||||
} else if fi.Mode().IsRegular() {
|
||||
err = copyFile(af, at)
|
||||
} else {
|
||||
return Entry{}, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
_ = os.RemoveAll(at)
|
||||
return Entry{}, err
|
||||
}
|
||||
s.usageDirty()
|
||||
s.copyMeta(cf, ct)
|
||||
nfi, err := os.Stat(at)
|
||||
if err != nil {
|
||||
return Entry{}, err
|
||||
}
|
||||
return toEntry(ct, nfi), nil
|
||||
}
|
||||
|
||||
func copyFile(src, dst string) error {
|
||||
in, err := os.Open(src)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer in.Close()
|
||||
fi, err := in.Stat()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(dst), 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
tmp, err := os.CreateTemp(filepath.Dir(dst), ".tmp-*")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer os.Remove(tmp.Name())
|
||||
if _, err := io.Copy(tmp, in); err != nil {
|
||||
tmp.Close()
|
||||
return err
|
||||
}
|
||||
if err := tmp.Sync(); err != nil {
|
||||
tmp.Close()
|
||||
return err
|
||||
}
|
||||
if err := tmp.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
_ = os.Chmod(tmp.Name(), 0o644)
|
||||
_ = os.Chtimes(tmp.Name(), fi.ModTime(), fi.ModTime())
|
||||
return os.Rename(tmp.Name(), dst)
|
||||
}
|
||||
|
||||
func copyTree(src, dst string) error {
|
||||
return filepath.WalkDir(src, func(p string, d fs.DirEntry, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
rel, _ := filepath.Rel(src, p)
|
||||
target := filepath.Join(dst, rel)
|
||||
switch {
|
||||
case d.IsDir():
|
||||
return os.MkdirAll(target, 0o755)
|
||||
case d.Type().IsRegular() && visible(d.Name()):
|
||||
return copyFile(p, target)
|
||||
}
|
||||
return nil // liens, fichiers spéciaux et fichiers internes ignorés
|
||||
})
|
||||
}
|
||||
|
||||
// Delete déplace un fichier ou un dossier dans la corbeille (.trash/, voir
|
||||
// trash.go), sans suppression physique. Un dossier non vide n'est supprimé que
|
||||
// si recursive.
|
||||
func (s *Store) Delete(rel string, recursive bool) error {
|
||||
return s.deleteAs(rel, recursive, "")
|
||||
}
|
||||
|
||||
// deleteAs est Delete en notant l'auteur de la suppression (by).
|
||||
func (s *Store) deleteAs(rel string, recursive bool, by string) error {
|
||||
c, abs, err := s.resolve(rel)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if c == "" {
|
||||
return ErrInvalidPath
|
||||
}
|
||||
fi, err := os.Lstat(abs)
|
||||
if err != nil {
|
||||
return mapErr(err)
|
||||
}
|
||||
if fi.IsDir() && !recursive {
|
||||
des, err := os.ReadDir(abs)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(des) > 0 {
|
||||
return ErrNotEmpty
|
||||
}
|
||||
}
|
||||
if err := s.trash(c, abs, by); err != nil {
|
||||
return err
|
||||
}
|
||||
s.removeThumb(c)
|
||||
s.removeShares(c)
|
||||
return nil
|
||||
}
|
||||
|
||||
// freeName renvoie c s'il est libre, sinon « nom (2).ext », « nom (3).ext »...
|
||||
// (format : suffixe avec %d) ; les dossiers n'ont pas d'extension.
|
||||
func (s *Store) freeName(c string, isDir bool, format string) string {
|
||||
if _, err := os.Lstat(absOf(s, c)); errors.Is(err, fs.ErrNotExist) {
|
||||
return c
|
||||
}
|
||||
dir, base, ext := path.Dir(c), path.Base(c), ""
|
||||
if !isDir {
|
||||
ext = path.Ext(base)
|
||||
base = strings.TrimSuffix(base, ext)
|
||||
}
|
||||
for i := 2; ; i++ {
|
||||
n := base + fmt.Sprintf(format, i) + ext
|
||||
if dir != "." {
|
||||
n = dir + "/" + n
|
||||
}
|
||||
if _, err := os.Lstat(absOf(s, n)); errors.Is(err, fs.ErrNotExist) {
|
||||
return n
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- Occupation disque -------------------------------------------------------------
|
||||
|
||||
func (s *Store) usageDirty() {
|
||||
s.usageMu.Lock()
|
||||
s.usageAt = time.Time{}
|
||||
s.usageMu.Unlock()
|
||||
}
|
||||
|
||||
// Usage renvoie le nombre d'octets occupés (fichiers, corbeille et historique
|
||||
// compris ; miniatures exclues). Le résultat est gardé 15 s, ou jusqu'à la
|
||||
// prochaine écriture.
|
||||
func (s *Store) Usage() int64 {
|
||||
s.usageMu.Lock()
|
||||
defer s.usageMu.Unlock()
|
||||
if time.Since(s.usageAt) < 15*time.Second {
|
||||
return s.usageSize
|
||||
}
|
||||
var total int64
|
||||
_ = filepath.WalkDir(s.root, func(p string, d fs.DirEntry, err error) error {
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
if d.IsDir() && p != s.root && d.Name() == thumbsDir {
|
||||
return filepath.SkipDir
|
||||
}
|
||||
if d.Type().IsRegular() {
|
||||
if fi, err := d.Info(); err == nil {
|
||||
total += fi.Size()
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
s.usageSize, s.usageAt = total, time.Now()
|
||||
return total
|
||||
}
|
||||
|
||||
// fileID : empreinte courte d'une chaîne (noms de fichiers dérivés).
|
||||
func fileID(s string) string {
|
||||
h := sha256.Sum256([]byte(s))
|
||||
return hex.EncodeToString(h[:8])
|
||||
}
|
||||
|
||||
// atomicWrite écrit data dans abs de façon atomique (fichier temporaire + rename).
|
||||
func atomicWrite(abs string, data []byte) error {
|
||||
tmp, err := os.CreateTemp(filepath.Dir(abs), ".tmp-*")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer os.Remove(tmp.Name()) // no-op après un rename réussi
|
||||
if _, err := tmp.Write(data); err != nil {
|
||||
tmp.Close()
|
||||
return err
|
||||
}
|
||||
if err := tmp.Sync(); err != nil {
|
||||
tmp.Close()
|
||||
return err
|
||||
}
|
||||
if err := tmp.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.Chmod(tmp.Name(), 0o644); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Rename(tmp.Name(), abs)
|
||||
}
|
||||
@@ -0,0 +1,526 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"errors"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/png"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func newStore(t *testing.T) *Store {
|
||||
t.Helper()
|
||||
s, err := New(t.TempDir())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func put(t *testing.T, s *Store, p, content string, o PutOptions) Entry {
|
||||
t.Helper()
|
||||
e, err := s.Put(p, strings.NewReader(content), o)
|
||||
if err != nil {
|
||||
t.Fatalf("Put(%s) : %v", p, err)
|
||||
}
|
||||
return e
|
||||
}
|
||||
|
||||
func read(t *testing.T, s *Store, p string) string {
|
||||
t.Helper()
|
||||
f, _, err := s.Open(p)
|
||||
if err != nil {
|
||||
t.Fatalf("Open(%s) : %v", p, err)
|
||||
}
|
||||
defer f.Close()
|
||||
b, _ := io.ReadAll(f)
|
||||
return string(b)
|
||||
}
|
||||
|
||||
func TestCleanRejectsHiddenAndTraversal(t *testing.T) {
|
||||
for _, bad := range []string{".trash", "a/.history/x", ".meta.json", "a/\x00b", `a\b`, "a/ b", strings.Repeat("x", 300), "a/\x01"} {
|
||||
if _, err := Clean(bad); err == nil {
|
||||
t.Errorf("Clean(%q) aurait dû échouer", bad)
|
||||
}
|
||||
}
|
||||
if c, err := Clean("/a/../b//c/"); err != nil || c != "b/c" {
|
||||
t.Errorf("Clean = %q, %v", c, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPutOpenListAnyFileType(t *testing.T) {
|
||||
s := newStore(t)
|
||||
put(t, s, "docs/rapport.pdf", "%PDF-1.4", PutOptions{By: "alice"})
|
||||
put(t, s, "docs/archive.tar.gz", "\x1f\x8b", PutOptions{})
|
||||
put(t, s, "docs/sans-extension", "x", PutOptions{})
|
||||
es, err := s.List("docs")
|
||||
if err != nil || len(es) != 3 {
|
||||
t.Fatalf("List = %v, %v", es, err)
|
||||
}
|
||||
if got := read(t, s, "docs/rapport.pdf"); got != "%PDF-1.4" {
|
||||
t.Errorf("contenu = %q", got)
|
||||
}
|
||||
if es[0].Name != "archive.tar.gz" || es[2].Name != "sans-extension" {
|
||||
t.Errorf("tri : %v", es)
|
||||
}
|
||||
st, _ := s.Stat("docs/rapport.pdf")
|
||||
if st.EditedBy != "alice" {
|
||||
t.Errorf("EditedBy = %q", st.EditedBy)
|
||||
}
|
||||
// Les fichiers temporaires et internes n'apparaissent jamais.
|
||||
root, _ := s.List("")
|
||||
for _, e := range root {
|
||||
if strings.HasPrefix(e.Name, ".") {
|
||||
t.Errorf("entrée cachée visible : %s", e.Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPutConflictModes(t *testing.T) {
|
||||
s := newStore(t)
|
||||
put(t, s, "a.txt", "un", PutOptions{})
|
||||
if _, err := s.Put("a.txt", strings.NewReader("deux"), PutOptions{}); !errors.Is(err, ErrExists) {
|
||||
t.Fatalf("fail : %v", err)
|
||||
}
|
||||
e := put(t, s, "a.txt", "trois", PutOptions{Conflict: "rename"})
|
||||
if e.Path != "a (2).txt" {
|
||||
t.Errorf("rename -> %q", e.Path)
|
||||
}
|
||||
e = put(t, s, "a.txt", "quatre", PutOptions{Conflict: "rename"})
|
||||
if e.Path != "a (3).txt" {
|
||||
t.Errorf("rename 2 -> %q", e.Path)
|
||||
}
|
||||
put(t, s, "a.txt", "cinq", PutOptions{Conflict: "overwrite"})
|
||||
if read(t, s, "a.txt") != "cinq" || read(t, s, "a (2).txt") != "trois" {
|
||||
t.Error("contenus inattendus après écrasement")
|
||||
}
|
||||
// Un dossier ne peut pas être écrasé par un fichier.
|
||||
if _, err := s.Mkdir("dir"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Put("dir", strings.NewReader("x"), PutOptions{Conflict: "overwrite"}); !errors.Is(err, ErrExists) {
|
||||
t.Errorf("dossier écrasé : %v", err)
|
||||
}
|
||||
// Un fichier ne peut pas servir de dossier parent.
|
||||
if _, err := s.Put("a.txt/enfant", strings.NewReader("x"), PutOptions{}); err == nil {
|
||||
t.Error("fichier utilisé comme dossier")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPutIfMatchAndLimit(t *testing.T) {
|
||||
s := newStore(t)
|
||||
e := put(t, s, "f.bin", "abc", PutOptions{})
|
||||
fi, _ := os.Stat(filepath.Join(s.root, "f.bin"))
|
||||
if _, err := s.Put("f.bin", strings.NewReader("zz"), PutOptions{Conflict: "overwrite", IfMatch: `W/"nope"`}); !errors.Is(err, ErrConflict) {
|
||||
t.Errorf("If-Match faux : %v", err)
|
||||
}
|
||||
if _, err := s.Put("f.bin", strings.NewReader("zz"), PutOptions{Conflict: "overwrite", IfMatch: ETag(fi)}); err != nil {
|
||||
t.Errorf("If-Match juste : %v", err)
|
||||
}
|
||||
_ = e
|
||||
_, err := s.Put("big.bin", strings.NewReader("0123456789"), PutOptions{Limit: 5, LimitErr: ErrQuota})
|
||||
if !errors.Is(err, ErrQuota) {
|
||||
t.Errorf("limite : %v", err)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(s.root, "big.bin")); err == nil {
|
||||
t.Error("fichier partiel conservé")
|
||||
}
|
||||
// Aucun fichier temporaire ne traîne.
|
||||
des, _ := os.ReadDir(s.root)
|
||||
for _, d := range des {
|
||||
if strings.HasPrefix(d.Name(), ".tmp-") {
|
||||
t.Errorf("temporaire : %s", d.Name())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPutPreservesModTime(t *testing.T) {
|
||||
s := newStore(t)
|
||||
want := time.Date(2020, 5, 17, 10, 0, 0, 0, time.UTC)
|
||||
e := put(t, s, "photo.jpg", "x", PutOptions{ModTime: want})
|
||||
if !e.ModTime.Equal(want) {
|
||||
t.Errorf("ModTime = %v", e.ModTime)
|
||||
}
|
||||
// Une date dans le futur lointain est ignorée.
|
||||
e = put(t, s, "futur.txt", "x", PutOptions{ModTime: time.Now().AddDate(10, 0, 0)})
|
||||
if e.ModTime.After(time.Now().Add(time.Hour)) {
|
||||
t.Errorf("date future acceptée : %v", e.ModTime)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHistoryOnOverwrite(t *testing.T) {
|
||||
s := newStore(t)
|
||||
put(t, s, "n.txt", "v1", PutOptions{ModTime: time.Now().Add(-3 * time.Hour)})
|
||||
put(t, s, "n.txt", "v2", PutOptions{Conflict: "overwrite", ModTime: time.Now().Add(-2 * time.Hour)})
|
||||
put(t, s, "n.txt", "v3", PutOptions{Conflict: "overwrite"})
|
||||
vs, err := s.Versions("n.txt")
|
||||
if err != nil || len(vs) != 2 {
|
||||
t.Fatalf("versions = %v, %v", vs, err)
|
||||
}
|
||||
f, _, err := s.OpenVersion("n.txt", vs[1].ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b, _ := io.ReadAll(f)
|
||||
f.Close()
|
||||
if string(b) != "v1" {
|
||||
t.Errorf("plus ancienne version = %q", b)
|
||||
}
|
||||
if _, err := s.Restore("n.txt", vs[1].ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if read(t, s, "n.txt") != "v1" {
|
||||
t.Error("restauration inopérante")
|
||||
}
|
||||
if vs, _ = s.Versions("n.txt"); len(vs) != 3 {
|
||||
t.Errorf("la restauration doit conserver l'état remplacé : %d versions", len(vs))
|
||||
}
|
||||
// Rétention.
|
||||
s.History.Keep = 2
|
||||
put(t, s, "n.txt", "v4", PutOptions{Conflict: "overwrite"})
|
||||
if vs, _ = s.Versions("n.txt"); len(vs) != 2 {
|
||||
t.Errorf("rétention : %d versions", len(vs))
|
||||
}
|
||||
// Historique désactivé.
|
||||
s.History.Keep = 0
|
||||
put(t, s, "z.txt", "a", PutOptions{})
|
||||
put(t, s, "z.txt", "b", PutOptions{Conflict: "overwrite"})
|
||||
if vs, _ = s.Versions("z.txt"); len(vs) != 0 {
|
||||
t.Errorf("historique désactivé : %d versions", len(vs))
|
||||
}
|
||||
}
|
||||
|
||||
func TestMoveCopyFolders(t *testing.T) {
|
||||
s := newStore(t)
|
||||
put(t, s, "src/a.txt", "A", PutOptions{})
|
||||
put(t, s, "src/sub/b.txt", "B", PutOptions{})
|
||||
if _, err := s.Copy("src", "copie"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if read(t, s, "copie/sub/b.txt") != "B" {
|
||||
t.Error("copie récursive")
|
||||
}
|
||||
if _, err := s.Copy("src", "src/dans"); !errors.Is(err, ErrInvalidPath) {
|
||||
t.Errorf("copie dans soi-même : %v", err)
|
||||
}
|
||||
if _, err := s.Move("src", "src/sub/x"); !errors.Is(err, ErrInvalidPath) {
|
||||
t.Errorf("déplacement dans soi-même : %v", err)
|
||||
}
|
||||
if _, err := s.Move("src", "copie"); !errors.Is(err, ErrExists) {
|
||||
t.Errorf("destination existante : %v", err)
|
||||
}
|
||||
if _, err := s.Move("src/a.txt", "deplace/renomme.txt"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if read(t, s, "deplace/renomme.txt") != "A" {
|
||||
t.Error("déplacement")
|
||||
}
|
||||
if _, _, err := s.Open("src/a.txt"); !errors.Is(err, ErrNotFound) {
|
||||
t.Errorf("ancien emplacement : %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTagsFollowMove(t *testing.T) {
|
||||
s := newStore(t)
|
||||
put(t, s, "a.txt", "x", PutOptions{})
|
||||
if err := s.EditTags([]string{"a.txt"}, []string{"Rapport", "rapport", "#Urgent"}, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
es, _ := s.List("")
|
||||
if len(es[0].Tags) != 2 {
|
||||
t.Fatalf("tags = %v", es[0].Tags)
|
||||
}
|
||||
if _, err := s.Move("a.txt", "b.txt"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
es, _ = s.List("")
|
||||
if len(es[0].Tags) != 2 {
|
||||
t.Errorf("tags perdus au déplacement : %v", es[0])
|
||||
}
|
||||
ts, _ := s.Tags()
|
||||
if len(ts) != 2 {
|
||||
t.Errorf("Tags() = %v", ts)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTrashRestoreAndName(t *testing.T) {
|
||||
s := newStore(t)
|
||||
put(t, s, "d/a.txt", "A", PutOptions{})
|
||||
if err := s.Delete("d/a.txt", false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, _, err := s.Open("d/a.txt"); !errors.Is(err, ErrNotFound) {
|
||||
t.Fatal("fichier encore présent")
|
||||
}
|
||||
put(t, s, "d/a.txt", "nouveau", PutOptions{}) // la place est prise
|
||||
items, _ := s.TrashItems()
|
||||
if len(items) != 1 {
|
||||
t.Fatalf("poubelle : %v", items)
|
||||
}
|
||||
e, err := s.RestoreTrash(items[0].ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if e.Path != "d/a (restauré 2).txt" || read(t, s, e.Path) != "A" {
|
||||
t.Errorf("restauration : %v", e)
|
||||
}
|
||||
// Dossier non vide : refus sans récursivité.
|
||||
if err := s.Delete("d", false); !errors.Is(err, ErrNotEmpty) {
|
||||
t.Errorf("dossier non vide : %v", err)
|
||||
}
|
||||
if err := s.Delete("d", true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSymlinkEscapeRefused(t *testing.T) {
|
||||
s := newStore(t)
|
||||
outside := t.TempDir()
|
||||
_ = os.WriteFile(filepath.Join(outside, "secret.txt"), []byte("secret"), 0o644)
|
||||
if err := os.Symlink(outside, filepath.Join(s.root, "lien")); err != nil {
|
||||
t.Skip("liens symboliques indisponibles")
|
||||
}
|
||||
if _, _, err := s.Open("lien/secret.txt"); err == nil {
|
||||
t.Error("lecture hors racine via lien symbolique")
|
||||
}
|
||||
if _, err := s.Put("lien/nouveau.txt", strings.NewReader("x"), PutOptions{}); err == nil {
|
||||
t.Error("écriture hors racine via lien symbolique")
|
||||
}
|
||||
es, _ := s.List("")
|
||||
for _, e := range es {
|
||||
if e.Name == "lien" {
|
||||
t.Error("lien symbolique listé")
|
||||
}
|
||||
}
|
||||
// Lien interne vers un dossier caché.
|
||||
_ = os.MkdirAll(filepath.Join(s.root, ".history"), 0o755)
|
||||
_ = os.Symlink(filepath.Join(s.root, ".history"), filepath.Join(s.root, "cache"))
|
||||
if _, err := s.List("cache"); err == nil {
|
||||
t.Error("accès aux dossiers internes via lien symbolique")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSearchNamesTagsAndText(t *testing.T) {
|
||||
s := newStore(t)
|
||||
put(t, s, "notes/Réseau.md", "# Plan\nLe VLAN 172.27.207.0/24 est routé", PutOptions{})
|
||||
put(t, s, "notes/photo.jpg", "VLAN dans un binaire", PutOptions{})
|
||||
put(t, s, "autre/budget.txt", "rien", PutOptions{})
|
||||
_ = s.EditTags([]string{"autre/budget.txt"}, []string{"Finance"}, nil)
|
||||
hits, _ := s.Search("172.27.207", Filter{}, 10)
|
||||
if len(hits) != 1 || hits[0].Name != "Réseau.md" || hits[0].Snippet == "" {
|
||||
t.Errorf("contenu : %v", hits)
|
||||
}
|
||||
if hits, _ = s.Search("reseau", Filter{}, 10); len(hits) != 1 {
|
||||
t.Errorf("nom sans accent : %v", hits)
|
||||
}
|
||||
if hits, _ = s.Search("vlan", Filter{}, 10); len(hits) != 1 { // le .jpg n'est pas indexé comme texte
|
||||
t.Errorf("binaire indexé : %v", hits)
|
||||
}
|
||||
if hits, _ = s.Search("", Filter{Tag: "finance"}, 10); len(hits) != 1 || hits[0].Name != "budget.txt" {
|
||||
t.Errorf("tag : %v", hits)
|
||||
}
|
||||
}
|
||||
|
||||
func TestShareFileAndFolder(t *testing.T) {
|
||||
s := newStore(t)
|
||||
put(t, s, "pub/a.txt", "A", PutOptions{})
|
||||
put(t, s, "pub/sub/b.txt", "B", PutOptions{})
|
||||
sh, err := s.CreateShare("pub", ShareOptions{TTL: time.Hour})
|
||||
if err != nil || !sh.IsDir || sh.Protected {
|
||||
t.Fatalf("CreateShare = %+v, %v", sh, err)
|
||||
}
|
||||
got, err := s.ResolveShare(sh.Token)
|
||||
if err != nil || got.Path != "pub" {
|
||||
t.Fatalf("ResolveShare = %+v, %v", got, err)
|
||||
}
|
||||
if p, err := SharedPath(got, "sub/b.txt"); err != nil || p != "pub/sub/b.txt" {
|
||||
t.Errorf("SharedPath = %q, %v", p, err)
|
||||
}
|
||||
for _, evil := range []string{"../secret", "sub/../../x", ".trash", "a/.history"} {
|
||||
if p, err := SharedPath(got, evil); err == nil && !strings.HasPrefix(p, "pub/") {
|
||||
t.Errorf("SharedPath(%q) = %q", evil, p)
|
||||
} else if err == nil && strings.Contains(p, "..") {
|
||||
t.Errorf("SharedPath(%q) = %q", evil, p)
|
||||
}
|
||||
}
|
||||
// Signature altérée, jeton inconnu.
|
||||
bad := sh.Token[:len(sh.Token)-2] + "xx"
|
||||
if _, err := s.ResolveShare(bad); !errors.Is(err, ErrNotFound) {
|
||||
t.Errorf("signature fausse : %v", err)
|
||||
}
|
||||
// Le lien suit un renommage et disparaît à la suppression.
|
||||
if _, err := s.Move("pub", "public"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got, err = s.ResolveShare(sh.Token); err != nil || got.Path != "public" {
|
||||
t.Errorf("après déplacement : %+v, %v", got, err)
|
||||
}
|
||||
if err := s.Delete("public", true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.ResolveShare(sh.Token); !errors.Is(err, ErrNotFound) {
|
||||
t.Errorf("après suppression : %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSharePasswordAndExpiry(t *testing.T) {
|
||||
s := newStore(t)
|
||||
put(t, s, "f.txt", "x", PutOptions{})
|
||||
sh, err := s.CreateShare("f.txt", ShareOptions{Password: "s3cret-mot-de-passe"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, _ := s.ResolveShare(sh.Token)
|
||||
if !got.Protected || !got.CheckPassword("s3cret-mot-de-passe") || got.CheckPassword("autre") {
|
||||
t.Error("mot de passe du lien")
|
||||
}
|
||||
if sh.IsDir {
|
||||
t.Error("IsDir")
|
||||
}
|
||||
c1, _ := s.UnlockCookie(got)
|
||||
c2, _ := s.UnlockCookie(got)
|
||||
if c1 == "" || c1 != c2 {
|
||||
t.Error("cookie de déverrouillage instable")
|
||||
}
|
||||
s.CountDownload(sh.ID)
|
||||
s.CountDownload(sh.ID)
|
||||
if got, _ = s.ResolveShare(sh.Token); got.Downloads != 2 {
|
||||
t.Errorf("téléchargements = %d", got.Downloads)
|
||||
}
|
||||
// Expiration.
|
||||
exp, _ := s.CreateShare("f.txt", ShareOptions{TTL: time.Millisecond})
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
if _, err := s.ResolveShare(exp.Token); !errors.Is(err, ErrNotFound) {
|
||||
t.Errorf("lien expiré : %v", err)
|
||||
}
|
||||
// Tout révoquer change la clé : les anciens liens deviennent invalides.
|
||||
if err := s.RevokeAllShares(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.ResolveShare(sh.Token); !errors.Is(err, ErrNotFound) {
|
||||
t.Errorf("après révocation générale : %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestZip(t *testing.T) {
|
||||
s := newStore(t)
|
||||
put(t, s, "d/a.txt", "AAA", PutOptions{})
|
||||
put(t, s, "d/sub/b.png", "BBB", PutOptions{})
|
||||
_ = os.WriteFile(filepath.Join(s.root, "d", ".cache"), []byte("interne"), 0o644)
|
||||
var buf bytes.Buffer
|
||||
item, err := s.SharedZipItem("d")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := WriteZip(&buf, []ZipItem{item}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
zr, err := zip.NewReader(bytes.NewReader(buf.Bytes()), int64(buf.Len()))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
names := map[string]string{}
|
||||
for _, f := range zr.File {
|
||||
rc, _ := f.Open()
|
||||
b, _ := io.ReadAll(rc)
|
||||
rc.Close()
|
||||
names[f.Name] = string(b)
|
||||
}
|
||||
if names["d/a.txt"] != "AAA" || names["d/sub/b.png"] != "BBB" {
|
||||
t.Errorf("contenu : %v", names)
|
||||
}
|
||||
for n := range names {
|
||||
if strings.Contains(n, ".cache") {
|
||||
t.Errorf("fichier interne archivé : %s", n)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func makePNG(w, h int) []byte {
|
||||
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), 128, 255})
|
||||
}
|
||||
}
|
||||
var buf bytes.Buffer
|
||||
_ = png.Encode(&buf, img)
|
||||
return buf.Bytes()
|
||||
}
|
||||
|
||||
func TestThumbs(t *testing.T) {
|
||||
s := newStore(t)
|
||||
put(t, s, "grande.png", string(makePNG(1200, 600)), PutOptions{})
|
||||
b, typ, _, err := s.Thumb("grande.png")
|
||||
if err != nil || typ != "image/png" {
|
||||
t.Fatalf("Thumb : %v %q", err, typ)
|
||||
}
|
||||
cfg, err := png.DecodeConfig(bytes.NewReader(b))
|
||||
if err != nil || cfg.Width != ThumbSize || cfg.Height != ThumbSize/2 {
|
||||
t.Errorf("dimensions = %v, %v", cfg, err)
|
||||
}
|
||||
// Seconde lecture : servie depuis .thumbs/.
|
||||
if _, err := os.Stat(filepath.Join(s.root, ".thumbs", "grande.png.thumb")); err != nil {
|
||||
t.Error("miniature non conservée")
|
||||
}
|
||||
// Une petite image n'est pas agrandie.
|
||||
put(t, s, "petite.png", string(makePNG(40, 20)), PutOptions{})
|
||||
b, _, _, _ = s.Thumb("petite.png")
|
||||
if cfg, _ := png.DecodeConfig(bytes.NewReader(b)); cfg.Width != 40 {
|
||||
t.Errorf("agrandissement : %v", cfg)
|
||||
}
|
||||
// Remplacement : la miniature est régénérée.
|
||||
put(t, s, "petite.png", string(makePNG(80, 80)), PutOptions{Conflict: "overwrite"})
|
||||
b, _, _, _ = s.Thumb("petite.png")
|
||||
if cfg, _ := png.DecodeConfig(bytes.NewReader(b)); cfg.Width != 80 {
|
||||
t.Errorf("miniature périmée : %v", cfg)
|
||||
}
|
||||
// Pas une image décodable.
|
||||
put(t, s, "x.pdf", "pdf", PutOptions{})
|
||||
if _, _, _, err := s.Thumb("x.pdf"); !errors.Is(err, ErrNotFound) {
|
||||
t.Errorf("PDF : %v", err)
|
||||
}
|
||||
put(t, s, "faux.png", "pas une image", PutOptions{})
|
||||
if _, _, _, err := s.Thumb("faux.png"); !errors.Is(err, ErrNotFound) {
|
||||
t.Errorf("image corrompue : %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOrient(t *testing.T) {
|
||||
src := image.NewRGBA(image.Rect(0, 0, 2, 1))
|
||||
src.Set(0, 0, color.RGBA{255, 0, 0, 255})
|
||||
src.Set(1, 0, color.RGBA{0, 0, 255, 255})
|
||||
got := orient(src, 6) // 90° horaire : 1 colonne de 2 lignes, rouge en haut
|
||||
if got.Bounds().Dx() != 1 || got.Bounds().Dy() != 2 || got.RGBAAt(0, 0).R != 255 || got.RGBAAt(0, 1).B != 255 {
|
||||
t.Errorf("rotation 6 : %v", got.Pix)
|
||||
}
|
||||
if o := exifOrientation([]byte("II*\x00\x08\x00\x00\x00\x01\x00\x12\x01\x03\x00\x01\x00\x00\x00\x06\x00\x00\x00")); o != 6 {
|
||||
t.Errorf("orientation EXIF = %d", o)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUsageAndDetails(t *testing.T) {
|
||||
s := newStore(t)
|
||||
put(t, s, "a/x.bin", strings.Repeat("x", 1000), PutOptions{})
|
||||
put(t, s, "a/b/y.bin", strings.Repeat("y", 500), PutOptions{})
|
||||
// 1500 octets de contenu, plus .meta.json (auteurs).
|
||||
if u := s.Usage(); u < 1500 || u > 2500 {
|
||||
t.Errorf("Usage = %d", u)
|
||||
}
|
||||
d, err := s.dirDetails("a")
|
||||
if err != nil || d.Files != 1 || d.Dirs != 1 || d.Total != 1500 || d.Count != 2 {
|
||||
t.Errorf("dirDetails = %+v, %v", d, err)
|
||||
}
|
||||
put(t, s, "img.png", string(makePNG(30, 10)), PutOptions{})
|
||||
fd, _ := s.fileDetails("img.png", s.metaSnapshot(), nil)
|
||||
if fd.Width != 30 || fd.Height != 10 {
|
||||
t.Errorf("fileDetails = %+v", fd)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,303 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"image"
|
||||
"image/draw"
|
||||
"image/gif"
|
||||
"image/jpeg"
|
||||
"image/png"
|
||||
"io"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Miniatures des images (JPEG, PNG, GIF), générées par le serveur à la
|
||||
// demande avec la bibliothèque standard et rangées dans .thumbs/ en miroir de
|
||||
// l'arborescence (a/b.jpg -> .thumbs/a/b.jpg.thumb). Une miniature plus ancienne
|
||||
// que son fichier est considérée comme périmée et régénérée. L'orientation
|
||||
// EXIF des JPEG est appliquée. Les autres formats (WebP, SVG...) sont affichés
|
||||
// tels quels par le navigateur, sans miniature.
|
||||
|
||||
const (
|
||||
// ThumbSize est le plus grand côté d'une miniature (pixels).
|
||||
ThumbSize = 480
|
||||
|
||||
maxThumbPixels = 25_000_000 // protège contre les « bombes » de décompression
|
||||
maxThumbSource = 80 << 20 // taille maximale du fichier source
|
||||
)
|
||||
|
||||
// isDecodableImage indique si la bibliothèque standard sait décoder le fichier.
|
||||
func isDecodableImage(name string) bool {
|
||||
switch strings.ToLower(path.Ext(name)) {
|
||||
case ".jpg", ".jpeg", ".png", ".gif":
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (s *Store) thumbAbs(c string, isDir bool) string {
|
||||
p := filepath.Join(s.root, thumbsDir, filepath.FromSlash(c))
|
||||
if isDir {
|
||||
return p
|
||||
}
|
||||
return p + ".thumb"
|
||||
}
|
||||
|
||||
// Thumb renvoie la miniature d'une image (créée si absente ou périmée), son
|
||||
// type MIME et sa date. ErrNotFound si le fichier n'est pas une image
|
||||
// décodable.
|
||||
func (s *Store) Thumb(rel string) ([]byte, string, time.Time, error) {
|
||||
c, abs, err := s.resolve(rel)
|
||||
if err != nil {
|
||||
return nil, "", time.Time{}, err
|
||||
}
|
||||
if c == "" || !isDecodableImage(c) {
|
||||
return nil, "", time.Time{}, ErrNotFound
|
||||
}
|
||||
src, err := os.Lstat(abs)
|
||||
if err != nil || !src.Mode().IsRegular() {
|
||||
return nil, "", time.Time{}, ErrNotFound
|
||||
}
|
||||
ta := s.thumbAbs(c, false)
|
||||
if ti, err := os.Stat(ta); err == nil && !ti.ModTime().Before(src.ModTime()) {
|
||||
if b, err := os.ReadFile(ta); err == nil {
|
||||
return b, sniffThumb(b), ti.ModTime(), nil
|
||||
}
|
||||
}
|
||||
if src.Size() > maxThumbSource {
|
||||
return nil, "", time.Time{}, ErrNotFound
|
||||
}
|
||||
s.thumbSem <- struct{}{}
|
||||
defer func() { <-s.thumbSem }()
|
||||
b, err := makeThumb(abs)
|
||||
if err != nil {
|
||||
return nil, "", time.Time{}, ErrNotFound
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(ta), 0o755); err == nil {
|
||||
_ = atomicWrite(ta, b)
|
||||
}
|
||||
return b, sniffThumb(b), time.Now(), nil
|
||||
}
|
||||
|
||||
func sniffThumb(b []byte) string {
|
||||
if bytes.HasPrefix(b, []byte("\x89PNG")) {
|
||||
return "image/png"
|
||||
}
|
||||
return "image/jpeg"
|
||||
}
|
||||
|
||||
func makeThumb(abs string) ([]byte, error) {
|
||||
f, err := os.Open(abs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer f.Close()
|
||||
cfg, format, err := image.DecodeConfig(f)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if cfg.Width < 1 || cfg.Height < 1 || cfg.Width*cfg.Height > maxThumbPixels {
|
||||
return nil, fmt.Errorf("image hors limites (%dx%d)", cfg.Width, cfg.Height)
|
||||
}
|
||||
if _, err := f.Seek(0, io.SeekStart); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
orientation := 1
|
||||
if format == "jpeg" {
|
||||
orientation = jpegOrientation(f)
|
||||
if _, err := f.Seek(0, io.SeekStart); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
var img image.Image
|
||||
switch format {
|
||||
case "jpeg":
|
||||
img, err = jpeg.Decode(f)
|
||||
case "png":
|
||||
img, err = png.Decode(f)
|
||||
case "gif":
|
||||
img, err = gif.Decode(f)
|
||||
default:
|
||||
err = fmt.Errorf("format %s non géré", format)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
b := img.Bounds()
|
||||
w, h := b.Dx(), b.Dy()
|
||||
scale := float64(ThumbSize) / float64(max(w, h))
|
||||
tw, th := w, h
|
||||
if scale < 1 {
|
||||
tw, th = max(1, int(float64(w)*scale+0.5)), max(1, int(float64(h)*scale+0.5))
|
||||
}
|
||||
out := orient(resize(img, tw, th), orientation)
|
||||
var buf bytes.Buffer
|
||||
if format == "jpeg" {
|
||||
// Fond blanc : un JPEG n'a pas de transparence, mais le décodage CMJN ou autre pourrait en avoir.
|
||||
err = jpeg.Encode(&buf, out, &jpeg.Options{Quality: 82})
|
||||
} else {
|
||||
err = png.Encode(&buf, out)
|
||||
}
|
||||
return buf.Bytes(), err
|
||||
}
|
||||
|
||||
// resize rééchantillonne img en w x h par moyenne de surface (filtre « boîte »),
|
||||
// en alpha prémultiplié ; sans agrandissement au-delà de la taille d'origine.
|
||||
func resize(img image.Image, w, h int) *image.RGBA {
|
||||
b := img.Bounds()
|
||||
src := image.NewRGBA(image.Rect(0, 0, b.Dx(), b.Dy()))
|
||||
draw.Draw(src, src.Bounds(), img, b.Min, draw.Src)
|
||||
if w == b.Dx() && h == b.Dy() {
|
||||
return src
|
||||
}
|
||||
wx, wy := boxWeights(b.Dx(), w), boxWeights(b.Dy(), h)
|
||||
dst := image.NewRGBA(image.Rect(0, 0, w, h))
|
||||
for dy := 0; dy < h; dy++ {
|
||||
for dx := 0; dx < w; dx++ {
|
||||
var acc [4]float64
|
||||
var total float64
|
||||
for _, y := range wy[dy] {
|
||||
row := y.i * src.Stride
|
||||
for _, x := range wx[dx] {
|
||||
k := y.w * x.w
|
||||
p := src.Pix[row+x.i*4:]
|
||||
acc[0] += k * float64(p[0])
|
||||
acc[1] += k * float64(p[1])
|
||||
acc[2] += k * float64(p[2])
|
||||
acc[3] += k * float64(p[3])
|
||||
total += k
|
||||
}
|
||||
}
|
||||
o := dst.PixOffset(dx, dy)
|
||||
for c := range acc {
|
||||
dst.Pix[o+c] = uint8(acc[c]/total + 0.5)
|
||||
}
|
||||
}
|
||||
}
|
||||
return dst
|
||||
}
|
||||
|
||||
// jpegOrientation lit l'orientation EXIF (1 à 8) d'un JPEG ; 1 si absente.
|
||||
func jpegOrientation(r io.Reader) int {
|
||||
buf := make([]byte, 128<<10)
|
||||
n, _ := io.ReadFull(r, buf)
|
||||
d := buf[:n]
|
||||
if len(d) < 4 || d[0] != 0xFF || d[1] != 0xD8 {
|
||||
return 1
|
||||
}
|
||||
i := 2
|
||||
for i+4 <= len(d) {
|
||||
if d[i] != 0xFF {
|
||||
return 1
|
||||
}
|
||||
marker := d[i+1]
|
||||
if marker == 0xDA || marker == 0xD9 { // début des données ou fin
|
||||
return 1
|
||||
}
|
||||
size := int(binary.BigEndian.Uint16(d[i+2:]))
|
||||
if size < 2 || i+2+size > len(d) {
|
||||
return 1
|
||||
}
|
||||
if marker == 0xE1 && size >= 16 && string(d[i+4:i+10]) == "Exif\x00\x00" {
|
||||
return exifOrientation(d[i+10 : i+2+size])
|
||||
}
|
||||
i += 2 + size
|
||||
}
|
||||
return 1
|
||||
}
|
||||
|
||||
func exifOrientation(t []byte) int {
|
||||
if len(t) < 8 {
|
||||
return 1
|
||||
}
|
||||
var bo binary.ByteOrder
|
||||
switch string(t[:2]) {
|
||||
case "II":
|
||||
bo = binary.LittleEndian
|
||||
case "MM":
|
||||
bo = binary.BigEndian
|
||||
default:
|
||||
return 1
|
||||
}
|
||||
off := int(bo.Uint32(t[4:]))
|
||||
if off < 8 || off+2 > len(t) {
|
||||
return 1
|
||||
}
|
||||
count := int(bo.Uint16(t[off:]))
|
||||
for k := 0; k < count; k++ {
|
||||
e := off + 2 + k*12
|
||||
if e+12 > len(t) {
|
||||
return 1
|
||||
}
|
||||
if bo.Uint16(t[e:]) == 0x0112 {
|
||||
if v := int(bo.Uint16(t[e+8:])); v >= 1 && v <= 8 {
|
||||
return v
|
||||
}
|
||||
return 1
|
||||
}
|
||||
}
|
||||
return 1
|
||||
}
|
||||
|
||||
// orient applique l'orientation EXIF o (2 : miroir horizontal, 3 : 180°,
|
||||
// 4 : miroir vertical, 5 : transposée, 6 : 90° horaire, 7 : transverse,
|
||||
// 8 : 90° anti-horaire).
|
||||
func orient(src *image.RGBA, o int) *image.RGBA {
|
||||
if o <= 1 || o > 8 {
|
||||
return src
|
||||
}
|
||||
w, h := src.Bounds().Dx(), src.Bounds().Dy()
|
||||
dw, dh := w, h
|
||||
if o >= 5 {
|
||||
dw, dh = h, w
|
||||
}
|
||||
dst := image.NewRGBA(image.Rect(0, 0, dw, dh))
|
||||
for y := 0; y < h; y++ {
|
||||
for x := 0; x < w; x++ {
|
||||
var nx, ny int
|
||||
switch o {
|
||||
case 2:
|
||||
nx, ny = w-1-x, y
|
||||
case 3:
|
||||
nx, ny = w-1-x, h-1-y
|
||||
case 4:
|
||||
nx, ny = x, h-1-y
|
||||
case 5:
|
||||
nx, ny = y, x
|
||||
case 6:
|
||||
nx, ny = h-1-y, x
|
||||
case 7:
|
||||
nx, ny = h-1-y, w-1-x
|
||||
case 8:
|
||||
nx, ny = y, w-1-x
|
||||
}
|
||||
copy(dst.Pix[dst.PixOffset(nx, ny):dst.PixOffset(nx, ny)+4], src.Pix[src.PixOffset(x, y):src.PixOffset(x, y)+4])
|
||||
}
|
||||
}
|
||||
return dst
|
||||
}
|
||||
|
||||
// Les opérations suivantes accompagnent Move/Delete. Elles sont « au mieux » :
|
||||
// une miniature manquante sera simplement régénérée.
|
||||
|
||||
func (s *Store) moveThumb(from, to string, isDir bool) {
|
||||
src, dst := s.thumbAbs(from, isDir), s.thumbAbs(to, isDir)
|
||||
if _, err := os.Stat(src); err != nil {
|
||||
return
|
||||
}
|
||||
_ = os.RemoveAll(dst)
|
||||
if err := os.MkdirAll(filepath.Dir(dst), 0o755); err == nil {
|
||||
_ = os.Rename(src, dst)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Store) removeThumb(c string) {
|
||||
_ = os.Remove(s.thumbAbs(c, false))
|
||||
_ = os.RemoveAll(s.thumbAbs(c, true))
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Corbeille : Delete range chaque élément supprimé dans .trash/<id>/, avec
|
||||
//
|
||||
// .trash/<id>/<nom> l'élément lui-même
|
||||
// .trash/<id>/.history/<nom> son historique de versions
|
||||
// .trash/<id>/.info.json chemin d'origine, date, auteur, tags et icônes
|
||||
//
|
||||
// L'élément peut être restauré à son emplacement d'origine ou supprimé
|
||||
// définitivement. Les éléments plus anciens que Settings.TrashDays (0 : jamais)
|
||||
// sont purgés automatiquement (Spaces.PurgeTrash).
|
||||
|
||||
const trashInfoFile = ".info.json"
|
||||
|
||||
const trashLayout = "20060102T150405.000000000"
|
||||
|
||||
var trashID = regexp.MustCompile(`^\d{8}T\d{6}\.\d{9}$`)
|
||||
|
||||
type trashInfo struct {
|
||||
Path string `json:"path"`
|
||||
Deleted time.Time `json:"deleted"`
|
||||
By string `json:"by,omitempty"`
|
||||
Meta map[string]itemMeta `json:"meta,omitempty"` // clés relatives à Path
|
||||
}
|
||||
|
||||
// TrashItem décrit un élément de la corbeille. Path est son chemin d'origine.
|
||||
type TrashItem struct {
|
||||
ID string
|
||||
Name string
|
||||
Path string
|
||||
IsDir bool
|
||||
Size int64
|
||||
Deleted time.Time
|
||||
By string
|
||||
}
|
||||
|
||||
func (s *Store) trashAbs(id string) string { return filepath.Join(s.root, trashDir, id) }
|
||||
|
||||
// trash range l'élément c (chemin absolu abs) dans une nouvelle entrée de
|
||||
// corbeille, avec son historique et ses métadonnées.
|
||||
func (s *Store) trash(c, abs, by string) error {
|
||||
now := time.Now().UTC()
|
||||
id := now.Format(trashLayout)
|
||||
dir := s.trashAbs(id)
|
||||
for i := 1; ; i++ { // deux suppressions dans la même nanoseconde
|
||||
if _, err := os.Lstat(dir); errors.Is(err, fs.ErrNotExist) {
|
||||
break
|
||||
}
|
||||
id = now.Add(time.Duration(i)).Format(trashLayout)
|
||||
dir = s.trashAbs(id)
|
||||
}
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.Rename(abs, filepath.Join(dir, filepath.Base(abs))); err != nil {
|
||||
_ = os.Remove(dir)
|
||||
return err
|
||||
}
|
||||
info := trashInfo{Path: c, Deleted: now, By: by, Meta: s.takeMeta(c)}
|
||||
if b, err := json.Marshal(info); err == nil {
|
||||
_ = atomicWrite(filepath.Join(dir, trashInfoFile), b)
|
||||
}
|
||||
s.trashHistory(c, dir)
|
||||
return nil
|
||||
}
|
||||
|
||||
// trashEntry lit une entrée de la corbeille : nom de l'élément et informations
|
||||
// (déduites du nom et de l'identifiant pour les entrées d'avant .info.json).
|
||||
func (s *Store) trashEntry(id string) (string, trashInfo, error) {
|
||||
if !trashID.MatchString(id) {
|
||||
return "", trashInfo{}, fmt.Errorf("%w : élément de corbeille %q", ErrInvalidPath, id)
|
||||
}
|
||||
dir := s.trashAbs(id)
|
||||
des, err := os.ReadDir(dir)
|
||||
if err != nil {
|
||||
return "", trashInfo{}, mapErr(err)
|
||||
}
|
||||
name := ""
|
||||
for _, de := range des {
|
||||
if !strings.HasPrefix(de.Name(), ".") {
|
||||
name = de.Name()
|
||||
break
|
||||
}
|
||||
}
|
||||
if name == "" {
|
||||
return "", trashInfo{}, ErrNotFound
|
||||
}
|
||||
var info trashInfo
|
||||
if b, err := os.ReadFile(filepath.Join(dir, trashInfoFile)); err == nil {
|
||||
_ = json.Unmarshal(b, &info)
|
||||
}
|
||||
if c, err := Clean(info.Path); err != nil || c == "" || path.Base(c) != name {
|
||||
info.Path = name // emplacement inconnu : restauration à la racine
|
||||
}
|
||||
if info.Deleted.IsZero() {
|
||||
info.Deleted, _ = time.Parse(trashLayout, id)
|
||||
}
|
||||
return name, info, nil
|
||||
}
|
||||
|
||||
// TrashItems liste la corbeille, les suppressions les plus récentes en premier.
|
||||
func (s *Store) TrashItems() ([]TrashItem, error) {
|
||||
des, err := os.ReadDir(filepath.Join(s.root, trashDir))
|
||||
if errors.Is(err, fs.ErrNotExist) {
|
||||
return []TrashItem{}, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := []TrashItem{}
|
||||
for _, de := range des {
|
||||
if !de.IsDir() || !trashID.MatchString(de.Name()) {
|
||||
continue
|
||||
}
|
||||
name, info, err := s.trashEntry(de.Name())
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
fi, err := os.Lstat(filepath.Join(s.trashAbs(de.Name()), name))
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
it := TrashItem{ID: de.Name(), Name: name, Path: info.Path, IsDir: fi.IsDir(), Deleted: info.Deleted, By: info.By}
|
||||
if !it.IsDir {
|
||||
it.Size = fi.Size()
|
||||
}
|
||||
out = append(out, it)
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool { return out[i].ID > out[j].ID })
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// TrashCount renvoie le nombre d'éléments dans la corbeille.
|
||||
func (s *Store) TrashCount() int {
|
||||
des, _ := os.ReadDir(filepath.Join(s.root, trashDir))
|
||||
n := 0
|
||||
for _, de := range des {
|
||||
if de.IsDir() && trashID.MatchString(de.Name()) {
|
||||
n++
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// RestoreTrash remet un élément à son emplacement d'origine (dossiers parents
|
||||
// recréés au besoin), sous un autre nom si la place est prise.
|
||||
func (s *Store) RestoreTrash(id string) (Entry, error) {
|
||||
name, info, err := s.trashEntry(id)
|
||||
if err != nil {
|
||||
return Entry{}, err
|
||||
}
|
||||
dir := s.trashAbs(id)
|
||||
src := filepath.Join(dir, name)
|
||||
fi, err := os.Lstat(src)
|
||||
if err != nil {
|
||||
return Entry{}, mapErr(err)
|
||||
}
|
||||
c := s.freeName(info.Path, fi.IsDir(), " (restauré %d)")
|
||||
_, abs, err := s.resolve(c)
|
||||
if err != nil {
|
||||
return Entry{}, err
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(abs), 0o755); err != nil {
|
||||
return Entry{}, err
|
||||
}
|
||||
if err := os.Rename(src, abs); err != nil {
|
||||
return Entry{}, mapErr(err)
|
||||
}
|
||||
moveAside(filepath.Join(dir, historyDir, name), s.historyAbs(c))
|
||||
s.putMeta(c, info.Meta)
|
||||
_ = os.RemoveAll(dir)
|
||||
if fi, err = os.Stat(abs); err != nil {
|
||||
return Entry{}, err
|
||||
}
|
||||
e := toEntry(c, fi)
|
||||
decorate(&e, s.metaSnapshot())
|
||||
return e, nil
|
||||
}
|
||||
|
||||
// DropTrash supprime définitivement un élément de la corbeille.
|
||||
func (s *Store) DropTrash(id string) error {
|
||||
if _, _, err := s.trashEntry(id); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.RemoveAll(s.trashAbs(id))
|
||||
}
|
||||
|
||||
// EmptyTrash vide la corbeille.
|
||||
func (s *Store) EmptyTrash() error {
|
||||
return s.purgeTrash(func(string) bool { return true })
|
||||
}
|
||||
|
||||
// PurgeTrashOlder supprime définitivement les éléments supprimés il y a plus de maxAge.
|
||||
func (s *Store) PurgeTrashOlder(maxAge time.Duration) error {
|
||||
limit := time.Now().Add(-maxAge)
|
||||
return s.purgeTrash(func(id string) bool {
|
||||
t, err := time.Parse(trashLayout, id)
|
||||
return err == nil && t.Before(limit)
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Store) purgeTrash(drop func(id string) bool) error {
|
||||
root := filepath.Join(s.root, trashDir)
|
||||
des, err := os.ReadDir(root)
|
||||
if errors.Is(err, fs.ErrNotExist) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var first error
|
||||
for _, de := range des {
|
||||
if !de.IsDir() || !trashID.MatchString(de.Name()) || !drop(de.Name()) {
|
||||
continue
|
||||
}
|
||||
if err := os.RemoveAll(filepath.Join(root, de.Name())); err != nil && first == nil {
|
||||
first = err
|
||||
}
|
||||
}
|
||||
return first
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Téléchargement d'un dossier ou d'une sélection en archive ZIP, générée en
|
||||
// flux (aucun fichier temporaire, mémoire constante).
|
||||
|
||||
// ZipItem est un fichier ou un dossier à archiver : Abs est son chemin sur le
|
||||
// disque, Name son nom dans l'archive.
|
||||
type ZipItem struct {
|
||||
Abs string
|
||||
Name string
|
||||
}
|
||||
|
||||
// compressed : extensions déjà compressées, stockées sans recompression.
|
||||
var compressed = map[string]bool{
|
||||
".zip": true, ".gz": true, ".tgz": true, ".bz2": true, ".xz": true, ".7z": true, ".rar": true, ".zst": true,
|
||||
".jpg": true, ".jpeg": true, ".png": true, ".gif": true, ".webp": true, ".avif": true, ".heic": true,
|
||||
".mp3": true, ".aac": true, ".ogg": true, ".opus": true, ".flac": true, ".m4a": true,
|
||||
".mp4": true, ".mkv": true, ".webm": true, ".mov": true, ".avi": true, ".m4v": true,
|
||||
".pdf": true, ".docx": true, ".xlsx": true, ".pptx": true, ".odt": true, ".ods": true, ".jar": true,
|
||||
}
|
||||
|
||||
// ZipItems traduit des chemins virtuels en éléments à archiver ; les doublons
|
||||
// de noms (même nom dans deux dossiers) reçoivent un suffixe « (2) ». Renvoie
|
||||
// aussi un nom d'archive : celui de l'élément unique, sinon « fichiers ».
|
||||
func (u *Space) ZipItems(paths []string) ([]ZipItem, string, error) {
|
||||
if len(paths) == 0 {
|
||||
return nil, "", ErrInvalidPath
|
||||
}
|
||||
var items []ZipItem
|
||||
used := map[string]bool{}
|
||||
for _, p := range paths {
|
||||
st, rel, err := u.route(p)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
c, abs, err := st.resolve(rel)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
name := path.Base(c)
|
||||
if c == "" {
|
||||
name = "fichiers" // racine de l'espace personnel
|
||||
}
|
||||
fi, err := os.Lstat(abs)
|
||||
if err != nil {
|
||||
return nil, "", mapErr(err)
|
||||
}
|
||||
if !fi.IsDir() && !fi.Mode().IsRegular() {
|
||||
return nil, "", ErrNotFound
|
||||
}
|
||||
items = append(items, ZipItem{Abs: abs, Name: uniqueZipName(name, used)})
|
||||
}
|
||||
archive := "fichiers"
|
||||
if len(items) == 1 {
|
||||
archive = items[0].Name
|
||||
}
|
||||
return items, archive, nil
|
||||
}
|
||||
|
||||
func uniqueZipName(name string, used map[string]bool) string {
|
||||
n := name
|
||||
for i := 2; used[strings.ToLower(n)]; i++ {
|
||||
ext := path.Ext(name)
|
||||
n = fmt.Sprintf("%s (%d)%s", strings.TrimSuffix(name, ext), i, ext)
|
||||
}
|
||||
used[strings.ToLower(n)] = true
|
||||
return n
|
||||
}
|
||||
|
||||
// SharedZipItem renvoie l'élément d'un lien de partage (ou d'un de ses
|
||||
// sous-dossiers) à archiver.
|
||||
func (s *Store) SharedZipItem(rel string) (ZipItem, error) {
|
||||
c, abs, err := s.resolve(rel)
|
||||
if err != nil {
|
||||
return ZipItem{}, err
|
||||
}
|
||||
if _, err := os.Lstat(abs); err != nil {
|
||||
return ZipItem{}, mapErr(err)
|
||||
}
|
||||
return ZipItem{Abs: abs, Name: path.Base(c)}, nil
|
||||
}
|
||||
|
||||
// WriteZip écrit les éléments dans w au format ZIP. Les liens symboliques, les
|
||||
// fichiers spéciaux et les fichiers internes (noms cachés) sont ignorés ; un
|
||||
// fichier illisible est sauté sans interrompre l'archive.
|
||||
func WriteZip(w io.Writer, items []ZipItem) error {
|
||||
zw := zip.NewWriter(w)
|
||||
for _, it := range items {
|
||||
fi, err := os.Lstat(it.Abs)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if !fi.IsDir() {
|
||||
if err := addZipFile(zw, it.Abs, it.Name, fi); err != nil {
|
||||
return err
|
||||
}
|
||||
continue
|
||||
}
|
||||
err = filepath.WalkDir(it.Abs, func(p string, d fs.DirEntry, err error) error {
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
if p != it.Abs && !visible(d.Name()) {
|
||||
if d.IsDir() {
|
||||
return filepath.SkipDir
|
||||
}
|
||||
return nil
|
||||
}
|
||||
rel, _ := filepath.Rel(it.Abs, p)
|
||||
name := it.Name
|
||||
if rel != "." {
|
||||
name = path.Join(it.Name, filepath.ToSlash(rel))
|
||||
}
|
||||
switch {
|
||||
case d.IsDir():
|
||||
h := &zip.FileHeader{Name: name + "/", Method: zip.Store}
|
||||
if info, err := d.Info(); err == nil {
|
||||
h.Modified = info.ModTime()
|
||||
}
|
||||
_, err := zw.CreateHeader(h)
|
||||
return err
|
||||
case d.Type().IsRegular():
|
||||
info, err := d.Info()
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
return addZipFile(zw, p, name, info)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return zw.Close()
|
||||
}
|
||||
|
||||
func addZipFile(zw *zip.Writer, abs, name string, fi fs.FileInfo) error {
|
||||
f, err := os.Open(abs)
|
||||
if err != nil {
|
||||
return nil // fichier illisible : sauté
|
||||
}
|
||||
defer f.Close()
|
||||
h := &zip.FileHeader{Name: name, Method: zip.Deflate, Modified: fi.ModTime()}
|
||||
if compressed[strings.ToLower(path.Ext(name))] {
|
||||
h.Method = zip.Store
|
||||
}
|
||||
h.UncompressedSize64 = uint64(fi.Size())
|
||||
out, err := zw.CreateHeader(h)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = io.Copy(out, f)
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,336 @@
|
||||
// Package tokens gère les jetons d'accès personnels à l'API : créés depuis
|
||||
// l'interface (sans expiration, révocables), ils permettent d'envoyer et de
|
||||
// télécharger des fichiers depuis un script (curl, rclone WebDAV non inclus...)
|
||||
// sans session de navigateur.
|
||||
//
|
||||
// Les jetons ne sont conservés que hachés (SHA-256) dans DATA_DIR/.tokens.json
|
||||
// (0600), rattachés à l'utilisateur qui les a créés : ils donnent accès à ses
|
||||
// fichiers comme sa session, mais ne peuvent pas gérer les jetons ni les comptes.
|
||||
package tokens
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/vblogio/upandown/internal/auth"
|
||||
)
|
||||
|
||||
const (
|
||||
fileName = ".tokens.json"
|
||||
prefix = "upd_"
|
||||
maxPerUser = 50
|
||||
MaxNameLen = 80
|
||||
touchEvery = time.Minute
|
||||
)
|
||||
|
||||
var (
|
||||
ErrNotFound = errors.New("jeton introuvable")
|
||||
ErrInvalid = errors.New("nom de jeton invalide")
|
||||
ErrTooMany = errors.New("trop de jetons : en révoquer avant d'en créer")
|
||||
)
|
||||
|
||||
// Token est un jeton enregistré (sans le secret, que seul son hachage représente).
|
||||
type Token struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
UserID string `json:"userId"`
|
||||
Hash string `json:"hash"`
|
||||
Created time.Time `json:"created"`
|
||||
LastUsed time.Time `json:"lastUsed,omitzero"`
|
||||
}
|
||||
|
||||
// Info est la vue d'un jeton renvoyée à l'interface.
|
||||
type Info struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Created time.Time `json:"created"`
|
||||
LastUsed time.Time `json:"lastUsed,omitzero"`
|
||||
}
|
||||
|
||||
func (t *Token) info() Info {
|
||||
return Info{ID: t.ID, Name: t.Name, Created: t.Created, LastUsed: t.LastUsed}
|
||||
}
|
||||
|
||||
// Store conserve les jetons dans dir/.tokens.json.
|
||||
type Store struct {
|
||||
mu sync.Mutex
|
||||
file string
|
||||
tokens []*Token
|
||||
}
|
||||
|
||||
// Open charge (ou crée) le fichier des jetons de dir.
|
||||
func Open(dir string) (*Store, error) {
|
||||
s := &Store{file: filepath.Join(dir, fileName)}
|
||||
b, err := os.ReadFile(s.file)
|
||||
switch {
|
||||
case errors.Is(err, os.ErrNotExist):
|
||||
case err != nil:
|
||||
return nil, err
|
||||
default:
|
||||
var d struct {
|
||||
Tokens []*Token `json:"tokens"`
|
||||
}
|
||||
if err := json.Unmarshal(b, &d); err != nil {
|
||||
return nil, errors.New(s.file + " invalide : " + err.Error())
|
||||
}
|
||||
s.tokens = d.Tokens
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
func (s *Store) save() error {
|
||||
b, err := json.Marshal(map[string]any{"tokens": s.tokens})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tmp, err := os.CreateTemp(filepath.Dir(s.file), ".tmp-*")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer os.Remove(tmp.Name())
|
||||
if err := tmp.Chmod(0o600); err != nil {
|
||||
tmp.Close()
|
||||
return err
|
||||
}
|
||||
if _, err := tmp.Write(b); err != nil {
|
||||
tmp.Close()
|
||||
return err
|
||||
}
|
||||
if err := tmp.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Rename(tmp.Name(), s.file)
|
||||
}
|
||||
|
||||
func hashOf(secret string) string {
|
||||
h := sha256.Sum256([]byte(secret))
|
||||
return hex.EncodeToString(h[:])
|
||||
}
|
||||
|
||||
func randomString(n int) string {
|
||||
b := make([]byte, n)
|
||||
_, _ = rand.Read(b)
|
||||
return base64.RawURLEncoding.EncodeToString(b)
|
||||
}
|
||||
|
||||
// Create crée un jeton pour userID ; le secret n'est renvoyé qu'ici.
|
||||
func (s *Store) Create(userID, name string) (string, Info, error) {
|
||||
name = strings.Join(strings.Fields(name), " ")
|
||||
if name == "" || !utf8.ValidString(name) || utf8.RuneCountInString(name) > MaxNameLen {
|
||||
return "", Info{}, ErrInvalid
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
n := 0
|
||||
for _, t := range s.tokens {
|
||||
if t.UserID == userID {
|
||||
n++
|
||||
}
|
||||
}
|
||||
if n >= maxPerUser {
|
||||
return "", Info{}, ErrTooMany
|
||||
}
|
||||
secret := prefix + randomString(32)
|
||||
t := &Token{ID: randomString(9), Name: name, UserID: userID, Hash: hashOf(secret), Created: time.Now().UTC().Truncate(time.Second)}
|
||||
s.tokens = append(s.tokens, t)
|
||||
if err := s.save(); err != nil {
|
||||
s.tokens = s.tokens[:len(s.tokens)-1]
|
||||
return "", Info{}, err
|
||||
}
|
||||
return secret, t.info(), nil
|
||||
}
|
||||
|
||||
// List renvoie les jetons de userID, les plus récents en premier.
|
||||
func (s *Store) List(userID string) []Info {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
out := []Info{}
|
||||
for _, t := range s.tokens {
|
||||
if t.UserID == userID {
|
||||
out = append(out, t.info())
|
||||
}
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool { return out[i].Created.After(out[j].Created) })
|
||||
return out
|
||||
}
|
||||
|
||||
// Revoke supprime un jeton de userID.
|
||||
func (s *Store) Revoke(userID, id string) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
for i, t := range s.tokens {
|
||||
if t.ID == id && t.UserID == userID {
|
||||
s.tokens = append(s.tokens[:i:i], s.tokens[i+1:]...)
|
||||
return s.save()
|
||||
}
|
||||
}
|
||||
return ErrNotFound
|
||||
}
|
||||
|
||||
// RevokeUser supprime tous les jetons d'un utilisateur (compte supprimé ou désactivé).
|
||||
func (s *Store) RevokeUser(userID string) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
kept := s.tokens[:0:0]
|
||||
for _, t := range s.tokens {
|
||||
if t.UserID != userID {
|
||||
kept = append(kept, t)
|
||||
}
|
||||
}
|
||||
if len(kept) != len(s.tokens) {
|
||||
s.tokens = kept
|
||||
_ = s.save()
|
||||
}
|
||||
}
|
||||
|
||||
// Lookup renvoie le jeton correspondant à secret.
|
||||
func (s *Store) Lookup(secret string) (Token, bool) {
|
||||
if !strings.HasPrefix(secret, prefix) {
|
||||
return Token{}, false
|
||||
}
|
||||
h := hashOf(secret)
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
for _, t := range s.tokens {
|
||||
if t.Hash == h {
|
||||
if time.Since(t.LastUsed) > touchEvery {
|
||||
t.LastUsed = time.Now().UTC().Truncate(time.Second)
|
||||
_ = s.save()
|
||||
}
|
||||
return *t, true
|
||||
}
|
||||
}
|
||||
return Token{}, false
|
||||
}
|
||||
|
||||
// --- HTTP ---------------------------------------------------------------------------------
|
||||
|
||||
type tokenKey struct{}
|
||||
|
||||
// FromContext renvoie le jeton qui a authentifié la requête (nil : session).
|
||||
func FromContext(ctx context.Context) *Token {
|
||||
t, _ := ctx.Value(tokenKey{}).(*Token)
|
||||
return t
|
||||
}
|
||||
|
||||
// Server expose les jetons en HTTP.
|
||||
type Server struct {
|
||||
Store *Store
|
||||
// Resolve renvoie l'utilisateur actif d'un identifiant de compte (nil, true :
|
||||
// pas d'authentification intégrée ; _, false : compte inexistant ou inactif).
|
||||
Resolve func(userID string) (*auth.User, bool)
|
||||
// UserID identifie l'utilisateur d'une requête de l'interface.
|
||||
UserID func(*http.Request) string
|
||||
}
|
||||
|
||||
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 bearer(r *http.Request) (string, bool) {
|
||||
scheme, tok, ok := strings.Cut(r.Header.Get("Authorization"), " ")
|
||||
if !ok || !strings.EqualFold(scheme, "Bearer") {
|
||||
return "", false
|
||||
}
|
||||
return strings.TrimSpace(tok), true
|
||||
}
|
||||
|
||||
// Middleware authentifie les requêtes porteuses d'un jeton (Authorization:
|
||||
// Bearer) et les transmet directement à mux avec l'utilisateur du jeton ; les
|
||||
// autres suivent next (session).
|
||||
func (s *Server) Middleware(next, mux http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
secret, ok := bearer(r)
|
||||
if !ok {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
t, valid := s.Store.Lookup(secret)
|
||||
var u *auth.User
|
||||
if valid {
|
||||
u, valid = s.Resolve(t.UserID)
|
||||
}
|
||||
if !valid {
|
||||
w.Header().Set("WWW-Authenticate", `Bearer error="invalid_token"`)
|
||||
writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "jeton d'accès invalide ou révoqué"})
|
||||
return
|
||||
}
|
||||
ctx := context.WithValue(r.Context(), tokenKey{}, &t)
|
||||
if u != nil {
|
||||
ctx = auth.WithUser(ctx, u)
|
||||
}
|
||||
mux.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
|
||||
// Register enregistre les routes des jetons.
|
||||
//
|
||||
// GET /api/tokens jetons de l'utilisateur
|
||||
// POST /api/tokens {"name"} nouveau jeton (renvoyé une seule fois)
|
||||
// DELETE /api/tokens/{id} révocation
|
||||
func (s *Server) Register(mux *http.ServeMux) {
|
||||
mux.HandleFunc("GET /api/tokens", s.session(func(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusOK, s.Store.List(s.UserID(r)))
|
||||
}))
|
||||
mux.HandleFunc("POST /api/tokens", s.session(func(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
Name string `json:"name"`
|
||||
}
|
||||
if json.NewDecoder(http.MaxBytesReader(w, r.Body, 4096)).Decode(&req) != nil {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "requête JSON invalide"})
|
||||
return
|
||||
}
|
||||
secret, info, err := s.Store.Create(s.UserID(r), req.Name)
|
||||
if err != nil {
|
||||
status := http.StatusInternalServerError
|
||||
if errors.Is(err, ErrInvalid) || errors.Is(err, ErrTooMany) {
|
||||
status = http.StatusBadRequest
|
||||
}
|
||||
writeJSON(w, status, map[string]string{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
writeJSON(w, http.StatusCreated, struct {
|
||||
Info
|
||||
Token string `json:"token"`
|
||||
}{info, secret})
|
||||
}))
|
||||
mux.HandleFunc("DELETE /api/tokens/{id}", s.session(func(w http.ResponseWriter, r *http.Request) {
|
||||
if err := s.Store.Revoke(s.UserID(r), r.PathValue("id")); err != nil {
|
||||
status := http.StatusInternalServerError
|
||||
if errors.Is(err, ErrNotFound) {
|
||||
status = http.StatusNotFound
|
||||
}
|
||||
writeJSON(w, status, map[string]string{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}))
|
||||
}
|
||||
|
||||
// session refuse les requêtes authentifiées par un jeton : un jeton ne peut
|
||||
// pas créer, lister ni révoquer de jetons.
|
||||
func (s *Server) session(h http.HandlerFunc) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
if FromContext(r.Context()) != nil {
|
||||
writeJSON(w, http.StatusForbidden, map[string]string{"error": "gestion des jetons réservée à la session de l'interface"})
|
||||
return
|
||||
}
|
||||
h(w, r)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user