Compare commits

...
3 Commits
Author SHA1 Message Date
venture 2beba7d010 acl rights 2026-11-16 14:11:25 +01:00
venture 8d48fadd01 api + cli 2026-11-16 13:12:36 +01:00
venture 4f18d94158 ignore data folder 2026-11-16 12:29:06 +01:00
15 changed files with 1939 additions and 29 deletions
+2
View File
@@ -3,3 +3,5 @@
*.db-shm *.db-shm
*.key *.key
.cluster-key-* .cluster-key-*
data
suggestions
+8 -8
View File
@@ -11,14 +11,14 @@ import (
type Permission = permission.Permission type Permission = permission.Permission
const ( const (
PermissionRead = permission.Read PermissionRead = permission.Read
PermissionWrite = permission.Write PermissionWrite = permission.Write
PermissionCreate = permission.Create PermissionCreate = permission.Create
PermissionDelete = permission.Delete PermissionDelete = permission.Delete
PermissionShare = permission.Share PermissionShare = permission.Share
PermissionManage = permission.Manage PermissionAdmin = permission.Admin
PermissionAdmin = permission.Admin PermissionRequest = permission.Request
PermissionAll = permission.All PermissionAll = permission.All
) )
type Entry struct { type Entry struct {
+8 -2
View File
@@ -12,6 +12,9 @@ import (
) )
func TestPermissionValidAndHas(t *testing.T) { func TestPermissionValidAndHas(t *testing.T) {
if PermissionAdmin != 32 || PermissionRequest != 64 {
t.Fatalf("bits = admin %d, request %d ; attendu 32 et 64", PermissionAdmin, PermissionRequest)
}
if !PermissionAll.Valid() { if !PermissionAll.Valid() {
t.Fatal("PermissionAll devrait être valide") t.Fatal("PermissionAll devrait être valide")
} }
@@ -25,8 +28,11 @@ func TestPermissionValidAndHas(t *testing.T) {
if !PermissionAdmin.Has(PermissionRead) { if !PermissionAdmin.Has(PermissionRead) {
t.Fatal("PermissionAdmin devrait impliquer PermissionRead") t.Fatal("PermissionAdmin devrait impliquer PermissionRead")
} }
if !PermissionAll.Has(PermissionManage) { if !PermissionAll.Has(PermissionRequest) {
t.Fatal("PermissionAll devrait contenir PermissionManage") t.Fatal("PermissionAll devrait contenir PermissionRequest")
}
if PermissionRequest.Has(PermissionRead) {
t.Fatal("PermissionRequest ne devrait pas impliquer PermissionRead")
} }
if PermissionRead.Has(PermissionWrite) { if PermissionRead.Has(PermissionWrite) {
t.Fatal("PermissionRead ne devrait pas impliquer PermissionWrite") t.Fatal("PermissionRead ne devrait pas impliquer PermissionWrite")
+56
View File
@@ -0,0 +1,56 @@
package api
import (
"net/http"
"mediarr/node"
)
type Server struct {
node *node.Node
}
func NewServer(n *node.Node) *Server {
return &Server{node: n}
}
func (s *Server) Handler() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("GET /api/health", s.handleHealth)
mux.HandleFunc("POST /api/login", s.handleLogin)
mux.Handle("POST /api/logout", s.requireAuth(http.HandlerFunc(s.handleLogout)))
mux.Handle("GET /api/me", s.requireAuth(http.HandlerFunc(s.handleMe)))
mux.Handle("POST /api/users", s.requireAuth(s.requireAdmin(http.HandlerFunc(s.handleCreateUser))))
mux.Handle("GET /api/libraries", s.requireAuth(http.HandlerFunc(s.handleListLibraries)))
mux.Handle("POST /api/libraries", s.requireAuth(http.HandlerFunc(s.handleCreateLibrary)))
mux.Handle("GET /api/documents/{id}", s.requireAuth(http.HandlerFunc(s.handleGetDocument)))
mux.Handle("GET /api/documents/{id}/children", s.requireAuth(http.HandlerFunc(s.handleListChildren)))
mux.Handle("POST /api/documents/{id}/children", s.requireAuth(http.HandlerFunc(s.handleCreateChild)))
mux.Handle("POST /api/documents/{id}/rename", s.requireAuth(http.HandlerFunc(s.handleRename)))
mux.Handle("PUT /api/documents/{id}/metadata", s.requireAuth(http.HandlerFunc(s.handleSetMetadata)))
mux.Handle("POST /api/documents/{id}/move", s.requireAuth(http.HandlerFunc(s.handleMove)))
mux.Handle("DELETE /api/documents/{id}", s.requireAuth(http.HandlerFunc(s.handleTrash)))
mux.Handle("POST /api/documents/{id}/restore", s.requireAuth(http.HandlerFunc(s.handleRestore)))
mux.Handle("GET /api/documents/{id}/versions", s.requireAuth(http.HandlerFunc(s.handleListVersions)))
mux.Handle("POST /api/documents/{id}/versions", s.requireAuth(http.HandlerFunc(s.handleUploadVersion)))
mux.Handle("GET /api/documents/{id}/head", s.requireAuth(http.HandlerFunc(s.handleGetHead)))
mux.Handle("POST /api/documents/{id}/head", s.requireAuth(http.HandlerFunc(s.handleSetHead)))
mux.Handle("POST /api/documents/{id}/retention", s.requireAuth(http.HandlerFunc(s.handleApplyRetention)))
mux.Handle("GET /api/versions/{id}", s.requireAuth(http.HandlerFunc(s.handleDownloadVersion)))
mux.Handle("DELETE /api/versions/{id}", s.requireAuth(http.HandlerFunc(s.handlePurgeVersion)))
mux.Handle("POST /api/versions/{id}/verify", s.requireAuth(http.HandlerFunc(s.handleVerifyVersion)))
mux.Handle("POST /api/maintenance/gc", s.requireAuth(s.requireAdmin(http.HandlerFunc(s.handleCollectGarbage))))
return mux
}
func (s *Server) handleHealth(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
}
+411
View File
@@ -0,0 +1,411 @@
package api
import (
"bytes"
"context"
"encoding/json"
"io"
"mime/multipart"
"net/http"
"net/http/httptest"
"testing"
"mediarr/auth"
"mediarr/ident"
"mediarr/identity"
"mediarr/node"
)
type apiTestEnv struct {
node node.Node
server *httptest.Server
}
func newAPITestEnv(t *testing.T) *apiTestEnv {
t.Helper()
t.Chdir(t.TempDir())
err, n := node.NewNode(node.NewNodeParams{
DatabaseName: "api",
StoragePath: "store",
ClusterKeyPath: "cluster.key",
})
if err != nil {
t.Fatalf("NewNode : %v", err)
}
t.Cleanup(func() {
if err := n.Close(); err != nil {
t.Errorf("Close : %v", err)
}
})
if err := n.Up(); err != nil {
t.Fatalf("Up : %v", err)
}
server := httptest.NewServer(NewServer(&n).Handler())
t.Cleanup(server.Close)
return &apiTestEnv{node: n, server: server}
}
func TestAPIWorkflow(t *testing.T) {
env := newAPITestEnv(t)
ctx := context.Background()
client := env.server.Client()
if _, err := env.node.Auth().CreateUser(ctx, auth.CreateUserParams{
Login: "admin",
Password: "password123",
Role: identity.RoleAdmin,
}); err != nil {
t.Fatalf("CreateUser(admin) : %v", err)
}
response, body := doJSON(t, client, http.MethodGet, env.server.URL+"/api/health", "", nil)
requireStatus(t, response, body, http.StatusOK)
response, body = doJSON(t, client, http.MethodGet, env.server.URL+"/api/me", "", nil)
requireStatus(t, response, body, http.StatusUnauthorized)
response, body = doJSON(t, client, http.MethodPost, env.server.URL+"/api/login", "", map[string]string{
"login": "admin",
"password": "password123",
})
requireStatus(t, response, body, http.StatusOK)
login := decodeBody[loginResponse](t, body)
if login.Token == "" || login.Principal.ID == "" || login.Account.Login != "admin" {
t.Fatalf("login = %+v", login)
}
if len(response.Cookies()) == 0 {
t.Fatal("cookie de session absent")
}
token := login.Token
response, body = doJSON(t, client, http.MethodGet, env.server.URL+"/api/me", token, nil)
requireStatus(t, response, body, http.StatusOK)
me := decodeBody[userDTO](t, body)
if me.Principal.ID != login.Principal.ID || me.Account.Login != "admin" {
t.Fatalf("me = %+v", me)
}
response, body = doJSON(t, client, http.MethodPost, env.server.URL+"/api/libraries", token, map[string]any{
"name": "Films",
})
requireStatus(t, response, body, http.StatusCreated)
library := decodeBody[documentDTO](t, body)
if library.Kind != "library" || library.Name != "Films" || library.PolicyID == nil {
t.Fatalf("bibliothèque = %+v", library)
}
response, body = doJSON(t, client, http.MethodGet, env.server.URL+"/api/libraries", token, nil)
requireStatus(t, response, body, http.StatusOK)
libraries := decodeBody[[]documentDTO](t, body)
if len(libraries) != 1 || libraries[0].ID != library.ID {
t.Fatalf("bibliothèques = %+v", libraries)
}
response, body = doJSON(t, client, http.MethodPost, env.server.URL+"/api/documents/"+library.ID+"/children", token, map[string]any{
"kind": "video",
"name": "film.mkv",
})
requireStatus(t, response, body, http.StatusCreated)
video := decodeBody[documentDTO](t, body)
if video.Kind != "video" || video.ParentID == nil || *video.ParentID != library.ID {
t.Fatalf("vidéo = %+v", video)
}
response, body = doUpload(t, client, env.server.URL+"/api/documents/"+video.ID+"/versions", token, "film.mkv", []byte("contenu v1"))
requireStatus(t, response, body, http.StatusCreated)
first := decodeBody[versionDTO](t, body)
if first.Seq != 1 || first.Size != int64(len("contenu v1")) || first.DocumentID != video.ID {
t.Fatalf("version 1 = %+v", first)
}
response, body = doJSON(t, client, http.MethodGet, env.server.URL+"/api/documents/"+video.ID+"/versions", token, nil)
requireStatus(t, response, body, http.StatusOK)
versions := decodeBody[[]versionDTO](t, body)
if len(versions) != 1 || versions[0].ID != first.ID {
t.Fatalf("versions = %+v", versions)
}
response, body = doJSON(t, client, http.MethodGet, env.server.URL+"/api/documents/"+video.ID+"/head", token, nil)
requireStatus(t, response, body, http.StatusOK)
head := decodeBody[struct {
Version *versionDTO `json:"version"`
}](t, body)
if head.Version == nil || head.Version.ID != first.ID {
t.Fatalf("head = %+v", head)
}
response, downloaded := doRaw(t, client, http.MethodGet, env.server.URL+"/api/versions/"+first.ID, token, nil, "")
requireStatus(t, response, downloaded, http.StatusOK)
if string(downloaded) != "contenu v1" {
t.Fatalf("contenu téléchargé = %q", downloaded)
}
response, body = doJSON(t, client, http.MethodPost, env.server.URL+"/api/documents/"+video.ID+"/head", token, map[string]string{
"version_id": first.ID,
})
requireStatus(t, response, body, http.StatusOK)
if decodeBody[versionDTO](t, body).ID != first.ID {
t.Fatal("version tête incohérente")
}
response, body = doUpload(t, client, env.server.URL+"/api/documents/"+video.ID+"/versions", token, "film.mkv", []byte("contenu v2"))
requireStatus(t, response, body, http.StatusCreated)
second := decodeBody[versionDTO](t, body)
if second.Seq != 2 {
t.Fatalf("version 2 = %+v", second)
}
response, body = doJSON(t, client, http.MethodPost, env.server.URL+"/api/documents/"+video.ID+"/head", token, map[string]string{
"version_id": second.ID,
})
requireStatus(t, response, body, http.StatusOK)
response, body = doJSON(t, client, http.MethodDelete, env.server.URL+"/api/versions/"+first.ID, token, nil)
requireStatus(t, response, body, http.StatusNoContent)
response, body = doJSON(t, client, http.MethodGet, env.server.URL+"/api/versions/"+first.ID, token, nil)
requireStatus(t, response, body, http.StatusGone)
response, body = doJSON(t, client, http.MethodPost, env.server.URL+"/api/documents/"+video.ID+"/retention", token, nil)
requireStatus(t, response, body, http.StatusOK)
retention := decodeBody[retentionDTO](t, body)
if retention.Kept < 1 {
t.Fatalf("rétention = %+v", retention)
}
response, body = doJSON(t, client, http.MethodPost, env.server.URL+"/api/versions/"+second.ID+"/verify", token, nil)
requireStatus(t, response, body, http.StatusNoContent)
response, body = doJSON(t, client, http.MethodPost, env.server.URL+"/api/documents/"+video.ID+"/rename", token, map[string]string{
"name": "film-renamed.mkv",
})
requireStatus(t, response, body, http.StatusOK)
if decodeBody[documentDTO](t, body).Name != "film-renamed.mkv" {
t.Fatal("renommage incohérent")
}
response, body = doJSON(t, client, http.MethodPut, env.server.URL+"/api/documents/"+video.ID+"/metadata", token, map[string]any{
"metadata": map[string]any{"tag": "test"},
})
requireStatus(t, response, body, http.StatusOK)
if string(decodeBody[documentDTO](t, body).Metadata) != `{"tag":"test"}` {
t.Fatalf("métadonnées = %s", body)
}
response, body = doJSON(t, client, http.MethodPost, env.server.URL+"/api/documents/"+library.ID+"/children", token, map[string]any{
"kind": "folder",
"name": "Dossier",
})
requireStatus(t, response, body, http.StatusCreated)
folder := decodeBody[documentDTO](t, body)
response, body = doJSON(t, client, http.MethodPost, env.server.URL+"/api/documents/"+video.ID+"/move", token, map[string]string{
"parent_id": folder.ID,
})
requireStatus(t, response, body, http.StatusOK)
moved := decodeBody[documentDTO](t, body)
if moved.ParentID == nil || *moved.ParentID != folder.ID {
t.Fatalf("déplacement = %+v", moved)
}
response, body = doJSON(t, client, http.MethodDelete, env.server.URL+"/api/documents/"+video.ID, token, nil)
requireStatus(t, response, body, http.StatusOK)
trashed := decodeBody[documentDTO](t, body)
if trashed.DeletedAt == nil {
t.Fatal("document non mis à la corbeille")
}
response, body = doJSON(t, client, http.MethodPost, env.server.URL+"/api/documents/"+video.ID+"/restore", token, nil)
requireStatus(t, response, body, http.StatusOK)
if decodeBody[documentDTO](t, body).DeletedAt != nil {
t.Fatal("document non restauré")
}
response, body = doJSON(t, client, http.MethodPost, env.server.URL+"/api/users", token, map[string]string{
"login": "member",
"password": "password123",
"role": identity.RoleMember,
})
requireStatus(t, response, body, http.StatusCreated)
response, body = doJSON(t, client, http.MethodPost, env.server.URL+"/api/login", "", map[string]string{
"login": "member",
"password": "password123",
})
requireStatus(t, response, body, http.StatusOK)
memberToken := decodeBody[loginResponse](t, body).Token
response, body = doJSON(t, client, http.MethodPost, env.server.URL+"/api/maintenance/gc", memberToken, nil)
requireStatus(t, response, body, http.StatusForbidden)
response, body = doJSON(t, client, http.MethodPost, env.server.URL+"/api/maintenance/gc", token, nil)
requireStatus(t, response, body, http.StatusOK)
response, body = doJSON(t, client, http.MethodPost, env.server.URL+"/api/logout", token, nil)
requireStatus(t, response, body, http.StatusNoContent)
response, body = doJSON(t, client, http.MethodGet, env.server.URL+"/api/me", token, nil)
requireStatus(t, response, body, http.StatusUnauthorized)
}
func TestAPILoginRejectsInvalidCredentials(t *testing.T) {
env := newAPITestEnv(t)
client := env.server.Client()
response, body := doJSON(t, client, http.MethodPost, env.server.URL+"/api/login", "", map[string]string{
"login": "missing",
"password": "password123",
})
requireStatus(t, response, body, http.StatusUnauthorized)
}
func TestAPIDocumentNotFound(t *testing.T) {
env := newAPITestEnv(t)
ctx := context.Background()
client := env.server.Client()
if _, err := env.node.Auth().CreateUser(ctx, auth.CreateUserParams{
Login: "admin",
Password: "password123",
Role: identity.RoleAdmin,
}); err != nil {
t.Fatalf("CreateUser : %v", err)
}
_, body := doJSON(t, client, http.MethodPost, env.server.URL+"/api/login", "", map[string]string{
"login": "admin",
"password": "password123",
})
token := decodeBody[loginResponse](t, body).Token
missing := ident.MustParse("00000000-0000-7000-8000-000000000999").String()
response, body := doJSON(t, client, http.MethodGet, env.server.URL+"/api/documents/"+missing, token, nil)
requireStatus(t, response, body, http.StatusNotFound)
}
func doJSON(t *testing.T, client *http.Client, method, url, token string, body any) (*http.Response, []byte) {
t.Helper()
var reader io.Reader
if body != nil {
encoded, err := json.Marshal(body)
if err != nil {
t.Fatalf("Marshal : %v", err)
}
reader = bytes.NewReader(encoded)
}
request, err := http.NewRequest(method, url, reader)
if err != nil {
t.Fatalf("NewRequest : %v", err)
}
if body != nil {
request.Header.Set("Content-Type", "application/json")
}
if token != "" {
request.Header.Set("Authorization", "Bearer "+token)
}
response, err := client.Do(request)
if err != nil {
t.Fatalf("%s %s : %v", method, url, err)
}
data, err := io.ReadAll(response.Body)
if err != nil {
_ = response.Body.Close()
t.Fatalf("ReadAll : %v", err)
}
_ = response.Body.Close()
return response, data
}
func doUpload(t *testing.T, client *http.Client, url, token, filename string, content []byte) (*http.Response, []byte) {
t.Helper()
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
part, err := writer.CreateFormFile("file", filename)
if err != nil {
t.Fatalf("CreateFormFile : %v", err)
}
if _, err := part.Write(content); err != nil {
t.Fatalf("Write : %v", err)
}
if err := writer.WriteField("message", "test"); err != nil {
t.Fatalf("WriteField : %v", err)
}
if err := writer.Close(); err != nil {
t.Fatalf("Close : %v", err)
}
request, err := http.NewRequest(http.MethodPost, url, body)
if err != nil {
t.Fatalf("NewRequest : %v", err)
}
request.Header.Set("Content-Type", writer.FormDataContentType())
request.Header.Set("Authorization", "Bearer "+token)
response, err := client.Do(request)
if err != nil {
t.Fatalf("POST %s : %v", url, err)
}
data, err := io.ReadAll(response.Body)
if err != nil {
_ = response.Body.Close()
t.Fatalf("ReadAll : %v", err)
}
_ = response.Body.Close()
return response, data
}
func doRaw(t *testing.T, client *http.Client, method, url, token string, body io.Reader, contentType string) (*http.Response, []byte) {
t.Helper()
request, err := http.NewRequest(method, url, body)
if err != nil {
t.Fatalf("NewRequest : %v", err)
}
if contentType != "" {
request.Header.Set("Content-Type", contentType)
}
if token != "" {
request.Header.Set("Authorization", "Bearer "+token)
}
response, err := client.Do(request)
if err != nil {
t.Fatalf("%s %s : %v", method, url, err)
}
data, err := io.ReadAll(response.Body)
if err != nil {
_ = response.Body.Close()
t.Fatalf("ReadAll : %v", err)
}
_ = response.Body.Close()
return response, data
}
func decodeBody[T any](t *testing.T, body []byte) T {
t.Helper()
var value T
if err := json.Unmarshal(body, &value); err != nil {
t.Fatalf("Unmarshal %s : %v", body, err)
}
return value
}
func requireStatus(t *testing.T, response *http.Response, body []byte, want int) {
t.Helper()
if response.StatusCode != want {
t.Fatalf("status = %d, attendu %d: %s", response.StatusCode, want, body)
}
}
+262
View File
@@ -0,0 +1,262 @@
package api
import (
"context"
"errors"
"net/http"
"strings"
"time"
"mediarr/auth"
"mediarr/identity"
)
const sessionCookieName = "mediarr_session"
type contextKey int
const (
userContextKey contextKey = iota
tokenContextKey
)
type loginRequest struct {
Login string `json:"login"`
Password string `json:"password"`
Label string `json:"label,omitempty"`
}
type loginResponse struct {
Token string `json:"token"`
Principal principalDTO `json:"principal"`
Account accountDTO `json:"account"`
}
type createUserRequest struct {
Login string `json:"login"`
Password string `json:"password"`
Role string `json:"role,omitempty"`
}
type userDTO struct {
Principal principalDTO `json:"principal"`
Account accountDTO `json:"account"`
}
type principalDTO struct {
ID string `json:"id"`
Kind string `json:"kind"`
Name string `json:"name"`
Status string `json:"status"`
CreatedAt int64 `json:"created_at"`
Groups []groupDTO `json:"groups"`
}
type groupDTO struct {
ID string `json:"id"`
Name string `json:"name"`
Status string `json:"status"`
Role string `json:"role"`
}
type accountDTO struct {
Login string `json:"login"`
State string `json:"state"`
MustChangePassword bool `json:"must_change_password"`
LastLoginAt *int64 `json:"last_login_at,omitempty"`
}
func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) {
var request loginRequest
if err := decodeJSON(w, r, &request); err != nil {
writeErrorFor(w, err)
return
}
user, err := s.node.Auth().Authenticate(r.Context(), request.Login, request.Password)
if err != nil {
writeErrorFor(w, err)
return
}
_, token, err := s.node.Auth().CreateSession(r.Context(), auth.CreateSessionParams{
PrincipalID: user.Principal.ID,
Kind: "web",
Label: request.Label,
UserAgent: r.UserAgent(),
})
if err != nil {
writeErrorFor(w, err)
return
}
http.SetCookie(w, &http.Cookie{
Name: sessionCookieName,
Value: token,
Path: "/",
MaxAge: int((30 * 24 * time.Hour).Seconds()),
HttpOnly: true,
SameSite: http.SameSiteLaxMode,
})
dto := userDTOFrom(user)
writeJSON(w, http.StatusOK, loginResponse{
Token: token,
Principal: dto.Principal,
Account: dto.Account,
})
}
func (s *Server) handleLogout(w http.ResponseWriter, r *http.Request) {
token := currentToken(r)
if token != "" {
if err := s.node.Auth().RevokeSessionByToken(r.Context(), token); err != nil && !errors.Is(err, auth.ErrInvalidSession) {
writeErrorFor(w, err)
return
}
}
http.SetCookie(w, &http.Cookie{
Name: sessionCookieName,
Value: "",
Path: "/",
MaxAge: -1,
HttpOnly: true,
SameSite: http.SameSiteLaxMode,
})
w.WriteHeader(http.StatusNoContent)
}
func (s *Server) handleMe(w http.ResponseWriter, r *http.Request) {
user := currentUser(r)
if user == nil {
writeError(w, http.StatusUnauthorized, auth.ErrInvalidSession.Error())
return
}
writeJSON(w, http.StatusOK, userDTOFrom(user))
}
func (s *Server) handleCreateUser(w http.ResponseWriter, r *http.Request) {
var request createUserRequest
if err := decodeJSON(w, r, &request); err != nil {
writeErrorFor(w, err)
return
}
role := request.Role
if role == "" {
role = identity.RoleMember
}
created, err := s.node.Auth().CreateUser(r.Context(), auth.CreateUserParams{
Login: request.Login,
Password: request.Password,
Role: role,
})
if err != nil {
writeErrorFor(w, err)
return
}
writeJSON(w, http.StatusCreated, userDTOFrom(created))
}
func (s *Server) requireAuth(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
token := extractToken(r)
if token == "" {
writeError(w, http.StatusUnauthorized, auth.ErrInvalidSession.Error())
return
}
_, user, err := s.node.Auth().ValidateSession(r.Context(), token)
if err != nil {
writeErrorFor(w, err)
return
}
ctx := context.WithValue(r.Context(), userContextKey, user)
ctx = context.WithValue(ctx, tokenContextKey, token)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
func (s *Server) requireAdmin(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user := currentUser(r)
if user == nil || !isAdmin(user) {
writeError(w, http.StatusForbidden, "droits administrateur requis")
return
}
next.ServeHTTP(w, r)
})
}
func extractToken(r *http.Request) string {
if header := r.Header.Get("Authorization"); header != "" {
if strings.HasPrefix(strings.ToLower(header), "bearer ") {
return strings.TrimSpace(header[len("bearer "):])
}
return ""
}
cookie, err := r.Cookie(sessionCookieName)
if err != nil {
return ""
}
return cookie.Value
}
func currentUser(r *http.Request) *auth.AuthenticatedUser {
user, _ := r.Context().Value(userContextKey).(*auth.AuthenticatedUser)
return user
}
func currentToken(r *http.Request) string {
token, _ := r.Context().Value(tokenContextKey).(string)
return token
}
func isAdmin(user *auth.AuthenticatedUser) bool {
for _, group := range user.Principal.Groups {
if group.Role == identity.RoleAdmin || group.Name == "admins" {
return true
}
}
return false
}
func userDTOFrom(user *auth.AuthenticatedUser) userDTO {
groups := make([]groupDTO, 0, len(user.Principal.Groups))
for _, group := range user.Principal.Groups {
groups = append(groups, groupDTO{
ID: group.ID.String(),
Name: group.Name,
Status: group.Status,
Role: group.Role,
})
}
var lastLoginAt *int64
if user.Account.LastLoginAt.Valid {
value := user.Account.LastLoginAt.Int64
lastLoginAt = &value
}
return userDTO{
Principal: principalDTO{
ID: user.Principal.ID.String(),
Kind: user.Principal.Kind,
Name: user.Principal.Name,
Status: user.Principal.Status,
CreatedAt: user.Principal.CreatedAt,
Groups: groups,
},
Account: accountDTO{
Login: user.Account.Login,
State: user.Account.State,
MustChangePassword: user.Account.MustChangePassword,
LastLoginAt: lastLoginAt,
},
}
}
+284
View File
@@ -0,0 +1,284 @@
package api
import (
"encoding/hex"
"fmt"
"io"
"mime"
"net/http"
"path/filepath"
"strconv"
"strings"
"mediarr/content"
"mediarr/ident"
)
type versionDTO struct {
ID string `json:"id"`
DocumentID string `json:"document_id"`
Seq int64 `json:"seq"`
ContentRoot string `json:"content_root"`
Size int64 `json:"size"`
Mime string `json:"mime,omitempty"`
AuthorID string `json:"author_id"`
Origin string `json:"origin"`
Message string `json:"message,omitempty"`
Pinned bool `json:"pinned"`
ContentPurgedAt *int64 `json:"content_purged_at,omitempty"`
CreatedAt int64 `json:"created_at"`
}
type setHeadRequest struct {
VersionID string `json:"version_id"`
}
type retentionDTO struct {
Purged []string `json:"purged"`
Kept int `json:"kept"`
}
type garbageCollectionDTO struct {
Blobs int `json:"blobs"`
Locations int `json:"locations"`
Bytes int64 `json:"bytes"`
}
func (s *Server) handleListVersions(w http.ResponseWriter, r *http.Request) {
documentID, err := idParam(r, "id")
if err != nil {
writeErrorFor(w, err)
return
}
versions, err := s.node.Content().ListVersions(r.Context(), actorID(r), documentID)
if err != nil {
writeErrorFor(w, err)
return
}
result := make([]versionDTO, 0, len(versions))
for i := range versions {
result = append(result, versionDTOFrom(&versions[i]))
}
writeJSON(w, http.StatusOK, result)
}
func (s *Server) handleUploadVersion(w http.ResponseWriter, r *http.Request) {
documentID, err := idParam(r, "id")
if err != nil {
writeErrorFor(w, err)
return
}
r.Body = http.MaxBytesReader(w, r.Body, maxUploadBody)
defer func() {
if r.MultipartForm != nil {
_ = r.MultipartForm.RemoveAll()
}
}()
file, header, err := r.FormFile("file")
if err != nil {
writeError(w, http.StatusBadRequest, "fichier requis")
return
}
defer file.Close()
origin := r.FormValue("origin")
if origin == "" {
origin = content.OriginUpload
}
if origin != content.OriginUpload && origin != content.OriginRestore {
writeError(w, http.StatusBadRequest, "origine invalide")
return
}
mimeType := strings.TrimSpace(r.FormValue("mime"))
if mimeType == "" {
mimeType = mime.TypeByExtension(strings.ToLower(filepath.Ext(header.Filename)))
}
if mimeType == "" {
mimeType = "application/octet-stream"
}
pinned := false
if raw := r.FormValue("pinned"); raw != "" {
parsed, err := strconv.ParseBool(raw)
if err != nil {
writeError(w, http.StatusBadRequest, "pinned invalide")
return
}
pinned = parsed
}
version, err := s.node.Content().CreateVersion(r.Context(), actorID(r), documentID, content.CreateVersionParams{
Source: file,
Mime: mimeType,
Origin: origin,
Message: r.FormValue("message"),
Pinned: pinned,
})
if err != nil {
writeErrorFor(w, err)
return
}
w.Header().Set("Location", "/api/versions/"+version.ID.String())
writeJSON(w, http.StatusCreated, versionDTOFrom(version))
}
func (s *Server) handleDownloadVersion(w http.ResponseWriter, r *http.Request) {
versionID, err := idParam(r, "id")
if err != nil {
writeErrorFor(w, err)
return
}
reader, version, err := s.node.Content().OpenVersion(r.Context(), actorID(r), versionID)
if err != nil {
writeErrorFor(w, err)
return
}
defer reader.Close()
contentType := version.Mime
if contentType == "" {
contentType = "application/octet-stream"
}
w.Header().Set("Content-Type", contentType)
w.Header().Set("Content-Length", strconv.FormatInt(version.Size, 10))
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%q", fmt.Sprintf("version-%d", version.Seq)))
w.WriteHeader(http.StatusOK)
_, _ = io.Copy(w, reader)
}
func (s *Server) handleGetHead(w http.ResponseWriter, r *http.Request) {
documentID, err := idParam(r, "id")
if err != nil {
writeErrorFor(w, err)
return
}
version, err := s.node.Content().HeadVersion(r.Context(), actorID(r), documentID)
if err != nil {
writeErrorFor(w, err)
return
}
if version == nil {
writeJSON(w, http.StatusOK, map[string]any{"version": nil})
return
}
writeJSON(w, http.StatusOK, map[string]any{"version": versionDTOFrom(version)})
}
func (s *Server) handleSetHead(w http.ResponseWriter, r *http.Request) {
documentID, err := idParam(r, "id")
if err != nil {
writeErrorFor(w, err)
return
}
var request setHeadRequest
if err := decodeJSON(w, r, &request); err != nil {
writeErrorFor(w, err)
return
}
versionID, err := ident.Parse(request.VersionID)
if err != nil {
writeError(w, http.StatusBadRequest, "version_id invalide")
return
}
version, err := s.node.Content().SetHeadVersion(r.Context(), actorID(r), documentID, versionID)
if err != nil {
writeErrorFor(w, err)
return
}
writeJSON(w, http.StatusOK, versionDTOFrom(version))
}
func (s *Server) handleApplyRetention(w http.ResponseWriter, r *http.Request) {
documentID, err := idParam(r, "id")
if err != nil {
writeErrorFor(w, err)
return
}
result, err := s.node.Content().ApplyRetention(r.Context(), actorID(r), documentID)
if err != nil {
writeErrorFor(w, err)
return
}
purged := make([]string, 0, len(result.Purged))
for _, id := range result.Purged {
purged = append(purged, id.String())
}
writeJSON(w, http.StatusOK, retentionDTO{Purged: purged, Kept: result.Kept})
}
func (s *Server) handlePurgeVersion(w http.ResponseWriter, r *http.Request) {
versionID, err := idParam(r, "id")
if err != nil {
writeErrorFor(w, err)
return
}
if err := s.node.Content().PurgeVersion(r.Context(), actorID(r), versionID); err != nil {
writeErrorFor(w, err)
return
}
w.WriteHeader(http.StatusNoContent)
}
func (s *Server) handleVerifyVersion(w http.ResponseWriter, r *http.Request) {
versionID, err := idParam(r, "id")
if err != nil {
writeErrorFor(w, err)
return
}
if err := s.node.Content().VerifyVersion(r.Context(), actorID(r), versionID); err != nil {
writeErrorFor(w, err)
return
}
w.WriteHeader(http.StatusNoContent)
}
func (s *Server) handleCollectGarbage(w http.ResponseWriter, r *http.Request) {
result, err := s.node.Content().CollectGarbage(r.Context())
if err != nil {
writeErrorFor(w, err)
return
}
writeJSON(w, http.StatusOK, garbageCollectionDTO{
Blobs: result.Blobs,
Locations: result.Locations,
Bytes: result.Bytes,
})
}
func versionDTOFrom(version *content.Version) versionDTO {
return versionDTO{
ID: version.ID.String(),
DocumentID: version.DocumentID.String(),
Seq: version.Seq,
ContentRoot: hex.EncodeToString(version.ContentRoot),
Size: version.Size,
Mime: version.Mime,
AuthorID: version.AuthorID.String(),
Origin: version.Origin,
Message: version.Message,
Pinned: version.Pinned,
ContentPurgedAt: version.ContentPurgedAt,
CreatedAt: version.CreatedAt,
}
}
+338
View File
@@ -0,0 +1,338 @@
package api
import (
"encoding/json"
"net/http"
"mediarr/document"
"mediarr/ident"
)
const defaultStoragePolicyID = "00000000-0000-7000-8000-000000000101"
type documentDTO struct {
ID string `json:"id"`
Kind string `json:"kind"`
OwnerID string `json:"owner_id"`
CreatedBy string `json:"created_by"`
ParentID *string `json:"parent_id,omitempty"`
Name string `json:"name"`
Path string `json:"path"`
Depth int64 `json:"depth"`
HeadVersionID *string `json:"head_version_id,omitempty"`
Metadata json.RawMessage `json:"metadata"`
PolicyID *string `json:"policy_id,omitempty"`
Visibility string `json:"visibility,omitempty"`
ACLInherit bool `json:"acl_inherit"`
Rev int64 `json:"rev"`
CreatedAt int64 `json:"created_at"`
UpdatedAt int64 `json:"updated_at"`
DeletedAt *int64 `json:"deleted_at,omitempty"`
}
type createLibraryRequest struct {
Name string `json:"name"`
PolicyID string `json:"policy_id,omitempty"`
Visibility string `json:"visibility,omitempty"`
ACLInherit *bool `json:"acl_inherit,omitempty"`
Metadata json.RawMessage `json:"metadata,omitempty"`
}
type createChildRequest struct {
Kind string `json:"kind"`
Name string `json:"name"`
ACLInherit *bool `json:"acl_inherit,omitempty"`
Metadata json.RawMessage `json:"metadata,omitempty"`
}
type renameRequest struct {
Name string `json:"name"`
}
type metadataRequest struct {
Metadata json.RawMessage `json:"metadata"`
}
type moveRequest struct {
ParentID string `json:"parent_id"`
}
func (s *Server) handleListLibraries(w http.ResponseWriter, r *http.Request) {
libraries, err := s.node.Documents().ListLibraries(r.Context(), actorID(r))
if err != nil {
writeErrorFor(w, err)
return
}
writeJSON(w, http.StatusOK, documentsDTO(libraries))
}
func (s *Server) handleCreateLibrary(w http.ResponseWriter, r *http.Request) {
var request createLibraryRequest
if err := decodeJSON(w, r, &request); err != nil {
writeErrorFor(w, err)
return
}
policyID := request.PolicyID
if policyID == "" {
policyID = defaultStoragePolicyID
}
parsedPolicyID, err := ident.Parse(policyID)
if err != nil {
writeError(w, http.StatusBadRequest, "policy_id invalide")
return
}
metadata, err := metadataString(request.Metadata)
if err != nil {
writeErrorFor(w, err)
return
}
created, err := s.node.Documents().CreateLibrary(r.Context(), actorID(r), document.CreateLibraryParams{
OwnerID: actorID(r),
CreatedBy: actorID(r),
Name: request.Name,
PolicyID: parsedPolicyID,
Visibility: request.Visibility,
ACLInherit: request.ACLInherit,
Metadata: metadata,
})
if err != nil {
writeErrorFor(w, err)
return
}
w.Header().Set("Location", "/api/documents/"+created.ID.String())
writeJSON(w, http.StatusCreated, documentDTOFrom(created))
}
func (s *Server) handleGetDocument(w http.ResponseWriter, r *http.Request) {
id, err := idParam(r, "id")
if err != nil {
writeErrorFor(w, err)
return
}
found, err := s.node.Documents().Get(r.Context(), actorID(r), id)
if err != nil {
writeErrorFor(w, err)
return
}
writeJSON(w, http.StatusOK, documentDTOFrom(found))
}
func (s *Server) handleListChildren(w http.ResponseWriter, r *http.Request) {
id, err := idParam(r, "id")
if err != nil {
writeErrorFor(w, err)
return
}
children, err := s.node.Documents().ListChildren(r.Context(), actorID(r), id)
if err != nil {
writeErrorFor(w, err)
return
}
writeJSON(w, http.StatusOK, documentsDTO(children))
}
func (s *Server) handleCreateChild(w http.ResponseWriter, r *http.Request) {
parentID, err := idParam(r, "id")
if err != nil {
writeErrorFor(w, err)
return
}
var request createChildRequest
if err := decodeJSON(w, r, &request); err != nil {
writeErrorFor(w, err)
return
}
metadata, err := metadataString(request.Metadata)
if err != nil {
writeErrorFor(w, err)
return
}
created, err := s.node.Documents().CreateChild(r.Context(), actorID(r), document.CreateChildParams{
Kind: request.Kind,
OwnerID: actorID(r),
CreatedBy: actorID(r),
ParentID: parentID,
Name: request.Name,
ACLInherit: request.ACLInherit,
Metadata: metadata,
})
if err != nil {
writeErrorFor(w, err)
return
}
w.Header().Set("Location", "/api/documents/"+created.ID.String())
writeJSON(w, http.StatusCreated, documentDTOFrom(created))
}
func (s *Server) handleRename(w http.ResponseWriter, r *http.Request) {
id, err := idParam(r, "id")
if err != nil {
writeErrorFor(w, err)
return
}
var request renameRequest
if err := decodeJSON(w, r, &request); err != nil {
writeErrorFor(w, err)
return
}
updated, err := s.node.Documents().Rename(r.Context(), actorID(r), id, request.Name)
if err != nil {
writeErrorFor(w, err)
return
}
writeJSON(w, http.StatusOK, documentDTOFrom(updated))
}
func (s *Server) handleSetMetadata(w http.ResponseWriter, r *http.Request) {
id, err := idParam(r, "id")
if err != nil {
writeErrorFor(w, err)
return
}
var request metadataRequest
if err := decodeJSON(w, r, &request); err != nil {
writeErrorFor(w, err)
return
}
metadata, err := metadataString(request.Metadata)
if err != nil {
writeErrorFor(w, err)
return
}
updated, err := s.node.Documents().SetMetadata(r.Context(), actorID(r), id, metadata)
if err != nil {
writeErrorFor(w, err)
return
}
writeJSON(w, http.StatusOK, documentDTOFrom(updated))
}
func (s *Server) handleMove(w http.ResponseWriter, r *http.Request) {
id, err := idParam(r, "id")
if err != nil {
writeErrorFor(w, err)
return
}
var request moveRequest
if err := decodeJSON(w, r, &request); err != nil {
writeErrorFor(w, err)
return
}
parentID, err := ident.Parse(request.ParentID)
if err != nil {
writeError(w, http.StatusBadRequest, "parent_id invalide")
return
}
moved, err := s.node.Documents().Move(r.Context(), actorID(r), id, parentID)
if err != nil {
writeErrorFor(w, err)
return
}
writeJSON(w, http.StatusOK, documentDTOFrom(moved))
}
func (s *Server) handleTrash(w http.ResponseWriter, r *http.Request) {
id, err := idParam(r, "id")
if err != nil {
writeErrorFor(w, err)
return
}
trashed, err := s.node.Documents().Trash(r.Context(), actorID(r), id)
if err != nil {
writeErrorFor(w, err)
return
}
writeJSON(w, http.StatusOK, documentDTOFrom(trashed))
}
func (s *Server) handleRestore(w http.ResponseWriter, r *http.Request) {
id, err := idParam(r, "id")
if err != nil {
writeErrorFor(w, err)
return
}
restored, err := s.node.Documents().Restore(r.Context(), actorID(r), id)
if err != nil {
writeErrorFor(w, err)
return
}
writeJSON(w, http.StatusOK, documentDTOFrom(restored))
}
func actorID(r *http.Request) ident.UUID {
user := currentUser(r)
if user == nil {
return ident.UUID{}
}
return user.Principal.ID
}
func documentsDTO(documents []document.Document) []documentDTO {
result := make([]documentDTO, 0, len(documents))
for i := range documents {
result = append(result, documentDTOFrom(&documents[i]))
}
return result
}
func documentDTOFrom(doc *document.Document) documentDTO {
dto := documentDTO{
ID: doc.ID.String(),
Kind: doc.Kind,
OwnerID: doc.OwnerID.String(),
CreatedBy: doc.CreatedBy.String(),
Name: doc.Name,
Path: doc.Path,
Depth: doc.Depth,
Metadata: json.RawMessage(doc.Metadata),
Visibility: doc.Visibility,
ACLInherit: doc.ACLInherit,
Rev: doc.Rev,
CreatedAt: doc.CreatedAt,
UpdatedAt: doc.UpdatedAt,
DeletedAt: doc.DeletedAt,
}
if doc.ParentID != nil {
value := doc.ParentID.String()
dto.ParentID = &value
}
if doc.HeadVersionID != nil {
value := doc.HeadVersionID.String()
dto.HeadVersionID = &value
}
if doc.PolicyID != nil {
value := doc.PolicyID.String()
dto.PolicyID = &value
}
return dto
}
+149
View File
@@ -0,0 +1,149 @@
package api
import (
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"mediarr/auth"
"mediarr/content"
"mediarr/document"
"mediarr/ident"
"mediarr/identity"
"mediarr/storage"
)
const (
maxJSONBody = 1 << 20
maxUploadBody = 2 << 30
)
func writeJSON(w http.ResponseWriter, status int, value any) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(status)
if status == http.StatusNoContent {
return
}
_ = json.NewEncoder(w).Encode(value)
}
func writeError(w http.ResponseWriter, status int, message string) {
if message == "" {
message = http.StatusText(status)
}
writeJSON(w, status, map[string]string{"error": message})
}
func writeErrorFor(w http.ResponseWriter, err error) {
status := statusForError(err)
message := err.Error()
switch status {
case http.StatusInternalServerError:
message = "erreur interne"
case http.StatusRequestEntityTooLarge:
message = "requête trop volumineuse"
}
writeError(w, status, message)
}
func statusForError(err error) int {
var maxBytes *http.MaxBytesError
if errors.As(err, &maxBytes) {
return http.StatusRequestEntityTooLarge
}
switch {
case errors.Is(err, auth.ErrInvalidCredentials),
errors.Is(err, auth.ErrInvalidSession):
return http.StatusUnauthorized
case errors.Is(err, auth.ErrAccountLocked),
errors.Is(err, auth.ErrAccountDisabled),
errors.Is(err, document.ErrPermissionDenied):
return http.StatusForbidden
case errors.Is(err, document.ErrDocumentNotFound),
errors.Is(err, document.ErrParentNotFound),
errors.Is(err, document.ErrPolicyNotFound),
errors.Is(err, content.ErrVersionNotFound),
errors.Is(err, content.ErrContentUnavailable),
errors.Is(err, storage.ErrNotFound):
return http.StatusNotFound
case errors.Is(err, document.ErrNameTaken),
errors.Is(err, document.ErrDocumentDeleted),
errors.Is(err, document.ErrParentDeleted),
errors.Is(err, auth.ErrLoginTaken),
errors.Is(err, content.ErrVersionIsHead),
errors.Is(err, content.ErrVersionMismatch),
errors.Is(err, content.ErrBlobUnavailable),
errors.Is(err, content.ErrBlobCorrupt):
return http.StatusConflict
case errors.Is(err, content.ErrContentPurged):
return http.StatusGone
case errors.Is(err, content.ErrStorageNotConfigured),
errors.Is(err, content.ErrStorageBackendMissing):
return http.StatusServiceUnavailable
case errors.Is(err, document.ErrInvalidName),
errors.Is(err, document.ErrInvalidKind),
errors.Is(err, document.ErrInvalidMetadata),
errors.Is(err, document.ErrInvalidParent),
errors.Is(err, document.ErrInvalidMove),
errors.Is(err, document.ErrCannotMoveRoot),
errors.Is(err, document.ErrInvalidVisibility),
errors.Is(err, document.ErrInvalidTrashBatch),
errors.Is(err, auth.ErrInvalidLogin),
errors.Is(err, auth.ErrWeakPassword),
errors.Is(err, identity.ErrInvalidRole),
errors.Is(err, content.ErrInvalidOrigin),
errors.Is(err, content.ErrInvalidSource),
errors.Is(err, content.ErrNoContentKind),
errors.Is(err, content.ErrNoStoragePolicy),
errors.Is(err, content.ErrInvalidRetention):
return http.StatusBadRequest
default:
return http.StatusInternalServerError
}
}
func decodeJSON(w http.ResponseWriter, r *http.Request, destination any) error {
r.Body = http.MaxBytesReader(w, r.Body, maxJSONBody)
decoder := json.NewDecoder(r.Body)
decoder.DisallowUnknownFields()
if err := decoder.Decode(destination); err != nil {
if errors.Is(err, io.EOF) {
return errors.New("corps JSON requis")
}
return err
}
var extra any
if err := decoder.Decode(&extra); !errors.Is(err, io.EOF) {
return errors.New("corps JSON invalide")
}
return nil
}
func metadataString(raw json.RawMessage) (string, error) {
if len(raw) == 0 {
return "{}", nil
}
if !json.Valid(raw) {
return "", fmt.Errorf("%w", document.ErrInvalidMetadata)
}
return string(raw), nil
}
func idParam(r *http.Request, name string) (ident.UUID, error) {
value := r.PathValue(name)
if value == "" {
return ident.UUID{}, errors.New("identifiant manquant")
}
id, err := ident.Parse(value)
if err != nil {
return ident.UUID{}, fmt.Errorf("identifiant invalide: %w", err)
}
return id, nil
}
+409 -7
View File
@@ -1,22 +1,424 @@
package main package main
import ( import (
"log" "context"
"encoding/json"
"errors"
"flag"
"fmt"
"net/http"
"os"
"os/signal"
"strings"
"syscall"
"time"
"mediarr/api"
"mediarr/auth"
"mediarr/document"
"mediarr/ident"
"mediarr/identity"
"mediarr/ingest"
"mediarr/node" "mediarr/node"
) )
func main() { const defaultStoragePolicyID = "00000000-0000-7000-8000-000000000101"
err, nodeA := node.NewNode(node.NewNodeParams{DatabaseName: "database"}) func main() {
if len(os.Args) < 2 {
usage()
os.Exit(2)
}
var err error
switch os.Args[1] {
case "serve":
err = runServe(os.Args[2:])
case "user":
err = runUser(os.Args[2:])
case "library":
err = runLibrary(os.Args[2:])
case "scan":
err = runScan(os.Args[2:])
case "import":
err = runImport(os.Args[2:])
case "help", "-h", "--help":
usage()
default:
usage()
err = fmt.Errorf("commande inconnue: %s", os.Args[1])
}
if err != nil { if err != nil {
log.Fatalln(err) fmt.Fprintln(os.Stderr, err)
os.Exit(1)
} }
}
defer nodeA.Close() func usage() {
fmt.Fprintln(os.Stderr, `Usage:
server serve [options]
server user create -login LOGIN -password PASSWORD [-role member|admin]
server user password -id UUID -password PASSWORD
server library create -owner UUID -name NAME [options]
server scan -actor UUID -parent UUID -path PATH [-prune]
server import -actor UUID -parent UUID -path PATH [-prune]
if err := nodeA.Up(); err != nil { Options de stockage:
log.Fatalln(err) -db NOM nom de la base SQLite (défaut: database)
-storage PATH répertoire de stockage (défaut: data)
-cluster-key PATH chemin de la clé cluster (défaut: cluster.key)`)
}
type nodeFlags struct {
database string
storage string
clusterKey string
}
func addNodeFlags(fs *flag.FlagSet) *nodeFlags {
flags := &nodeFlags{}
fs.StringVar(&flags.database, "db", "database", "nom de la base SQLite")
fs.StringVar(&flags.storage, "storage", "data", "répertoire de stockage")
fs.StringVar(&flags.clusterKey, "cluster-key", "cluster.key", "chemin de la clé cluster")
return flags
}
func (f *nodeFlags) open() (node.Node, error) {
err, n := node.NewNode(node.NewNodeParams{
DatabaseName: f.database,
StoragePath: f.storage,
ClusterKeyPath: f.clusterKey,
})
if err != nil {
return node.Node{}, err
}
if err := n.Up(); err != nil {
_ = n.Close()
return node.Node{}, err
}
return n, nil
}
func runServe(args []string) error {
fs := flag.NewFlagSet("serve", flag.ExitOnError)
addr := fs.String("addr", ":8080", "adresse HTTP")
flags := addNodeFlags(fs)
if err := fs.Parse(args); err != nil {
return err
}
n, err := flags.open()
if err != nil {
return err
}
defer n.Close()
server := &http.Server{
Addr: *addr,
Handler: api.NewServer(&n).Handler(),
ReadHeaderTimeout: 10 * time.Second,
IdleTimeout: 120 * time.Second,
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
go func() {
<-ctx.Done()
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
_ = server.Shutdown(shutdownCtx)
}()
fmt.Printf("Mediarr écoute sur %s\n", *addr)
if err := server.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
return err
}
return nil
}
func runUser(args []string) error {
if len(args) == 0 {
return errors.New("usage: server user create|password [options]")
}
switch args[0] {
case "create":
return runUserCreate(args[1:])
case "password":
return runUserPassword(args[1:])
default:
return fmt.Errorf("sous-commande user inconnue: %s", args[0])
}
}
func runUserCreate(args []string) error {
fs := flag.NewFlagSet("user create", flag.ExitOnError)
login := fs.String("login", "", "login")
password := fs.String("password", "", "mot de passe (ou MEDIARR_PASSWORD)")
role := fs.String("role", identity.RoleMember, "rôle: member ou admin")
flags := addNodeFlags(fs)
if err := fs.Parse(args); err != nil {
return err
}
if *login == "" {
return errors.New("login requis")
}
passwordValue := *password
if passwordValue == "" {
passwordValue = os.Getenv("MEDIARR_PASSWORD")
}
if passwordValue == "" {
return errors.New("mot de passe requis (-password ou MEDIARR_PASSWORD)")
}
n, err := flags.open()
if err != nil {
return err
}
defer n.Close()
created, err := n.Auth().CreateUser(context.Background(), auth.CreateUserParams{
Login: *login,
Password: passwordValue,
Role: *role,
})
if err != nil {
return err
}
return printJSON(map[string]any{
"id": created.Principal.ID.String(),
"login": created.Account.Login,
"role": *role,
})
}
func runUserPassword(args []string) error {
fs := flag.NewFlagSet("user password", flag.ExitOnError)
id := fs.String("id", "", "UUID du principal")
password := fs.String("password", "", "mot de passe (ou MEDIARR_PASSWORD)")
flags := addNodeFlags(fs)
if err := fs.Parse(args); err != nil {
return err
}
principalID, err := parseID(*id, "id")
if err != nil {
return err
}
passwordValue := *password
if passwordValue == "" {
passwordValue = os.Getenv("MEDIARR_PASSWORD")
}
if passwordValue == "" {
return errors.New("mot de passe requis (-password ou MEDIARR_PASSWORD)")
}
n, err := flags.open()
if err != nil {
return err
}
defer n.Close()
if err := n.Auth().SetPassword(context.Background(), principalID, passwordValue); err != nil {
return err
}
return printJSON(map[string]string{"status": "updated", "id": principalID.String()})
}
func runLibrary(args []string) error {
if len(args) == 0 || args[0] != "create" {
return errors.New("usage: server library create -owner UUID -name NAME [options]")
}
return runLibraryCreate(args[1:])
}
func runLibraryCreate(args []string) error {
fs := flag.NewFlagSet("library create", flag.ExitOnError)
owner := fs.String("owner", "", "UUID du propriétaire")
name := fs.String("name", "", "nom de la bibliothèque")
policy := fs.String("policy", defaultStoragePolicyID, "UUID de la politique de stockage")
visibility := fs.String("visibility", document.VisibilityPrivate, "PRIVATE, CLUSTER, FEDERATED ou PUBLIC")
aclInherit := fs.Bool("acl-inherit", true, "héritage ACL")
metadata := fs.String("metadata", "{}", "métadonnées JSON")
flags := addNodeFlags(fs)
if err := fs.Parse(args); err != nil {
return err
}
ownerID, err := parseID(*owner, "owner")
if err != nil {
return err
}
policyID, err := parseID(*policy, "policy")
if err != nil {
return err
}
if *name == "" {
return errors.New("name requis")
}
if !json.Valid([]byte(*metadata)) {
return errors.New("metadata doit être un JSON valide")
}
n, err := flags.open()
if err != nil {
return err
}
defer n.Close()
created, err := n.Documents().CreateLibrary(context.Background(), ownerID, document.CreateLibraryParams{
OwnerID: ownerID,
CreatedBy: ownerID,
Name: *name,
PolicyID: policyID,
Visibility: *visibility,
ACLInherit: aclInherit,
Metadata: *metadata,
})
if err != nil {
return err
}
return printJSON(map[string]any{
"id": created.ID.String(),
"kind": created.Kind,
"name": created.Name,
"path": created.Path,
"owner_id": created.OwnerID.String(),
"policy_id": created.PolicyID.String(),
"visibility": created.Visibility,
})
}
func runScan(args []string) error {
fs := flag.NewFlagSet("scan", flag.ExitOnError)
actor := fs.String("actor", "", "UUID du principal")
parent := fs.String("parent", "", "UUID du document parent")
root := fs.String("path", "", "chemin à scanner")
prune := fs.Bool("prune", false, "supprimer les documents absents du disque")
flags := addNodeFlags(fs)
if err := fs.Parse(args); err != nil {
return err
}
actorID, err := parseID(*actor, "actor")
if err != nil {
return err
}
parentID, err := parseID(*parent, "parent")
if err != nil {
return err
}
if strings.TrimSpace(*root) == "" {
return errors.New("path requis")
}
n, err := flags.open()
if err != nil {
return err
}
defer n.Close()
result, err := n.Ingest().ScanWithOptions(context.Background(), actorID, parentID, *root, ingest.ScanOptions{Prune: *prune})
if err != nil {
return err
}
if err := printJSON(scanOutputFrom(result)); err != nil {
return err
}
if result.HasErrors() {
return fmt.Errorf("scan terminé avec %d erreur(s)", len(result.Errors))
}
return nil
}
func runImport(args []string) error {
fs := flag.NewFlagSet("import", flag.ExitOnError)
actor := fs.String("actor", "", "UUID du principal")
parent := fs.String("parent", "", "UUID du document parent")
root := fs.String("path", "", "fichier ou dossier à importer")
prune := fs.Bool("prune", false, "supprimer les documents absents du disque")
flags := addNodeFlags(fs)
if err := fs.Parse(args); err != nil {
return err
}
actorID, err := parseID(*actor, "actor")
if err != nil {
return err
}
parentID, err := parseID(*parent, "parent")
if err != nil {
return err
}
if strings.TrimSpace(*root) == "" {
return errors.New("path requis")
}
n, err := flags.open()
if err != nil {
return err
}
defer n.Close()
result, err := n.Ingest().ImportWithOptions(context.Background(), actorID, parentID, *root, ingest.ScanOptions{Prune: *prune})
if err != nil {
return err
}
if err := printJSON(scanOutputFrom(result)); err != nil {
return err
}
if result.HasErrors() {
return fmt.Errorf("import terminé avec %d erreur(s)", len(result.Errors))
}
return nil
}
type scanOutput struct {
Files int `json:"files"`
Directories int `json:"directories"`
Created int `json:"created"`
Updated int `json:"updated"`
Unchanged int `json:"unchanged"`
Pruned int `json:"pruned"`
Errors []string `json:"errors,omitempty"`
}
func scanOutputFrom(result ingest.ScanResult) scanOutput {
output := scanOutput{
Files: result.Files,
Directories: result.Directories,
Created: result.Created,
Updated: result.Updated,
Unchanged: result.Unchanged,
Pruned: result.Pruned,
}
for _, scanErr := range result.Errors {
output.Errors = append(output.Errors, scanErr.Error())
}
return output
}
func parseID(value, name string) (ident.UUID, error) {
if strings.TrimSpace(value) == "" {
return ident.UUID{}, fmt.Errorf("%s requis", name)
}
id, err := ident.Parse(value)
if err != nil {
return ident.UUID{}, fmt.Errorf("%s invalide: %w", name, err)
} }
return id, nil
}
func printJSON(value any) error {
encoder := json.NewEncoder(os.Stdout)
encoder.SetIndent("", " ")
return encoder.Encode(value)
} }
+3 -3
View File
@@ -172,9 +172,9 @@ func TestApplyRetention(t *testing.T) {
t.Fatalf("second résultat = %+v, attendu 0 purgée et 3 conservées", again) t.Fatalf("second résultat = %+v, attendu 0 purgée et 3 conservées", again)
} }
manageDenied := NewService(*env.db, env.store, testBackendID, &testAuthorizer{allowed: permission.Write}) adminDenied := NewService(*env.db, env.store, testBackendID, &testAuthorizer{allowed: permission.Write})
if _, err := manageDenied.ApplyRetention(ctx, env.owner.ID, env.videoID); !errors.Is(err, document.ErrPermissionDenied) { if _, err := adminDenied.ApplyRetention(ctx, env.owner.ID, env.videoID); !errors.Is(err, document.ErrPermissionDenied) {
t.Fatalf("ApplyRetention sans Manage : erreur = %v, attendu ErrPermissionDenied", err) t.Fatalf("ApplyRetention sans Admin : erreur = %v, attendu ErrPermissionDenied", err)
} }
if _, err := env.db.WriteDB.ExecContext(ctx, if _, err := env.db.WriteDB.ExecContext(ctx,
+1 -1
View File
@@ -44,7 +44,7 @@ func (s *Service) ApplyRetention(ctx context.Context, actorID, documentID ident.
if documentRow.DeletedAt.Valid { if documentRow.DeletedAt.Valid {
return RetentionResult{}, fmt.Errorf("%w: %s", document.ErrDocumentDeleted, documentID) return RetentionResult{}, fmt.Errorf("%w: %s", document.ErrDocumentDeleted, documentID)
} }
if err := s.can(ctx, actorID, documentID, permission.Manage); err != nil { if err := s.can(ctx, actorID, documentID, permission.Admin); err != nil {
return RetentionResult{}, err return RetentionResult{}, err
} }
+4 -4
View File
@@ -173,9 +173,9 @@ func TestEnforcementRename(t *testing.T) {
t.Fatalf("sans Write : erreur = %v, attendu ErrPermissionDenied", err) t.Fatalf("sans Write : erreur = %v, attendu ErrPermissionDenied", err)
} }
authorizer.grant(writer.ID, folder.ID, permission.Manage) authorizer.grant(writer.ID, folder.ID, permission.Request)
if _, err := service.Rename(ctx, writer.ID, folder.ID, "Aventure"); !errors.Is(err, ErrPermissionDenied) { if _, err := service.Rename(ctx, writer.ID, folder.ID, "Aventure"); !errors.Is(err, ErrPermissionDenied) {
t.Fatalf("avec Manage seul : erreur = %v, attendu ErrPermissionDenied", err) t.Fatalf("avec Request seul : erreur = %v, attendu ErrPermissionDenied", err)
} }
authorizer.grant(writer.ID, folder.ID, permission.Write) authorizer.grant(writer.ID, folder.ID, permission.Write)
@@ -198,10 +198,10 @@ func TestEnforcementMove(t *testing.T) {
authorizer.active = map[ident.UUID]bool{mover.ID: true} authorizer.active = map[ident.UUID]bool{mover.ID: true}
if _, err := service.Move(ctx, mover.ID, folder.ID, libraryB.ID); !errors.Is(err, ErrPermissionDenied) { if _, err := service.Move(ctx, mover.ID, folder.ID, libraryB.ID); !errors.Is(err, ErrPermissionDenied) {
t.Fatalf("sans Manage : erreur = %v, attendu ErrPermissionDenied", err) t.Fatalf("sans Admin : erreur = %v, attendu ErrPermissionDenied", err)
} }
authorizer.grant(mover.ID, folder.ID, permission.Manage) authorizer.grant(mover.ID, folder.ID, permission.Admin)
if _, err := service.Move(ctx, mover.ID, folder.ID, libraryB.ID); !errors.Is(err, ErrPermissionDenied) { if _, err := service.Move(ctx, mover.ID, folder.ID, libraryB.ID); !errors.Is(err, ErrPermissionDenied) {
t.Fatalf("sans Create sur la cible : erreur = %v, attendu ErrPermissionDenied", err) t.Fatalf("sans Create sur la cible : erreur = %v, attendu ErrPermissionDenied", err)
} }
+1 -1
View File
@@ -82,7 +82,7 @@ func (s *Service) Move(ctx context.Context, actorID, documentID, newParentID ide
if err != nil { if err != nil {
return nil, err return nil, err
} }
if err := s.can(ctx, actorID, documentID, permission.Manage); err != nil { if err := s.can(ctx, actorID, documentID, permission.Admin); err != nil {
return nil, err return nil, err
} }
if document.ParentID == nil { if document.ParentID == nil {
+3 -3
View File
@@ -8,8 +8,8 @@ const (
Create Create
Delete Delete
Share Share
Manage
Admin Admin
Request
) )
const All = Read | const All = Read |
@@ -17,8 +17,8 @@ const All = Read |
Create | Create |
Delete | Delete |
Share | Share |
Manage | Admin |
Admin Request
func (p Permission) Valid() bool { func (p Permission) Valid() bool {
return p > 0 && p <= All return p > 0 && p <= All