package auth import ( "context" "crypto/pbkdf2" "crypto/rand" "crypto/sha256" "crypto/subtle" "encoding/json" "errors" "fmt" "log/slog" "os" "path/filepath" "regexp" "sort" "strconv" "strings" "sync" "time" "unicode/utf8" "github.com/jackc/pgx/v5" "github.com/vblogio/upandown/internal/catalog" ) // 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, ou dans la table // accounts du catalogue PostgreSQL (UseCatalog) quand plusieurs instances // partagent les mêmes comptes. type Accounts struct { mu sync.Mutex file string byID map[string]*Account // mode fichier db *catalog.DB // mode catalogue dummy string // empreinte factice : égalise le temps de réponse d'un identifiant inconnu } const accountsTable = "accounts" // accountsTimeout borne une opération sur le catalogue. const accountsTimeout = 30 * time.Second // 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: list, err := decodeAccounts(b) if err != nil { return nil, errors.New(a.file + " invalide : " + err.Error()) } for _, acc := range list { a.byID[acc.ID] = acc } } a.dummy = hashPassword("mot de passe factice") return a, nil } func decodeAccounts(b []byte) ([]*Account, error) { var d struct { Accounts []*Account `json:"accounts"` } err := json.Unmarshal(b, &d) return d.Accounts, err } // UseCatalog range désormais les comptes dans le catalogue. Au premier // branchement, le fichier .accounts.json est repris en base (une seule fois, // sans écraser un compte déjà présent) puis renommé en .accounts.json.imported. // À appeler au démarrage, avant de servir des requêtes. func (a *Accounts) UseCatalog(db *catalog.DB) error { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute) defer cancel() err := db.ImportFileOnce(ctx, "global", "accounts", a.file, func(ctx context.Context, tx pgx.Tx, b []byte) error { list, err := decodeAccounts(b) if err != nil { return err } m := make(map[string]*Account, len(list)) for _, acc := range list { m[acc.ID] = acc } return catalog.InsertDocs(ctx, tx, accountsTable, m) }) if err != nil { return fmt.Errorf("reprise des comptes : %w", err) } a.mu.Lock() a.db, a.byID = db, nil a.mu.Unlock() return nil } // snapshot renvoie une copie de tous les comptes. func (a *Accounts) snapshot() (map[string]*Account, error) { if a.db != nil { ctx, cancel := context.WithTimeout(context.Background(), accountsTimeout) defer cancel() return catalog.AllDocs[Account](ctx, a.db, accountsTable) } a.mu.Lock() defer a.mu.Unlock() return cloneAccounts(a.byID), nil } // update applique fn à tous les comptes, de façon atomique : une erreur de fn // n'enregistre rien. En mode catalogue, fn s'exécute sous un verrou commun à // toutes les instances et peut être rejouée. func (a *Accounts) update(fn func(map[string]*Account) error) error { if a.db != nil { ctx, cancel := context.WithTimeout(context.Background(), accountsTimeout) defer cancel() return catalog.UpdateDocs(ctx, a.db, accountsTable, fn) } a.mu.Lock() defer a.mu.Unlock() next := cloneAccounts(a.byID) if err := fn(next); err != nil { return err } if err := a.save(next); err != nil { return err } a.byID = next return nil } func cloneAccounts(m map[string]*Account) map[string]*Account { out := make(map[string]*Account, len(m)) for id, acc := range m { c := *acc out[id] = &c } return out } // save écrit le fichier ; appelé sous mu. func (a *Accounts) save(m map[string]*Account) error { list := make([]*Account, 0, len(m)) for _, acc := range m { 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) { if a.db != nil { ctx, cancel := context.WithTimeout(context.Background(), accountsTimeout) defer cancel() acc, err := catalog.GetDoc[Account](ctx, a.db, accountsTable, id) if err != nil { slog.Error("comptes : lecture", "id", id, "err", err) } if acc == nil { return Account{}, false } return *acc, true } a.mu.Lock() defer a.mu.Unlock() if acc, ok := a.byID[id]; ok { return *acc, true } return Account{}, false } // all renvoie les comptes (vide en cas d'erreur, journalisée). func (a *Accounts) all() (map[string]*Account, bool) { m, err := a.snapshot() if err != nil { slog.Error("comptes : lecture", "err", err) return map[string]*Account{}, false } return m, true } // List renvoie tous les comptes, du plus ancien au plus récent. func (a *Accounts) List() []AccountInfo { m, _ := a.all() out := make([]AccountInfo, 0, len(m)) for _, acc := range m { 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 { m, _ := a.all() return len(m) } // hasAdmin indique si un administrateur actif existe dans m. func hasAdmin(m map[string]*Account) bool { for _, acc := range m { 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. Faux si les comptes sont illisibles. func (a *Accounts) NeedsSetup() bool { m, ok := a.all() return ok && !hasAdmin(m) } // PendingCount renvoie le nombre d'inscriptions en attente de validation. func (a *Accounts) PendingCount() int { m, _ := a.all() n := 0 for _, acc := range m { if acc.Status == StatusPending { n++ } } return n } func byUsername(m map[string]*Account, name string) *Account { for _, acc := range m { 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 created := time.Now().UTC().Truncate(time.Second) var out Account err := a.update(func(m map[string]*Account) error { if _, exists := m[username]; exists { return ErrAccountExists } acc := &Account{ID: username, Username: username, Name: name, Email: email, Provider: ProviderLocal, Role: n.Role, Status: n.Status, Hash: hash, Created: created} if !hasAdmin(m) { acc.Role, acc.Status = RoleAdmin, StatusActive } if acc.Role != RoleAdmin { acc.Role = RoleUser } if acc.Status != StatusPending && acc.Status != StatusDisabled { acc.Status = StatusActive } m[acc.ID] = acc out = *acc return nil }) if err != nil { return Account{}, err } return out, 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)) var acc *Account if a.db != nil { ctx, cancel := context.WithTimeout(context.Background(), accountsTimeout) found, err := catalog.FindDoc[Account](ctx, a.db, accountsTable, "username", username) cancel() if err != nil { return Account{}, err } if found != nil && found.Provider == ProviderLocal { acc = found } } else { a.mu.Lock() if p := byUsername(a.byID, username); p != nil { c := *p acc = &c } a.mu.Unlock() } hash := a.dummy if acc != nil { hash = acc.Hash } if !checkPassword(hash, password) || acc == nil { return Account{}, ErrBadCredentials } var out Account var refused error err := a.update(func(m map[string]*Account) error { refused = nil cur := m[acc.ID] if cur == nil || cur.Hash != hash { // supprimé ou mot de passe changé entre-temps return ErrBadCredentials } out = *cur switch cur.Status { case StatusPending: refused = ErrPending case StatusDisabled: refused = ErrDisabled default: cur.LastLogin = time.Now().UTC().Truncate(time.Second) out = *cur } return nil }) if err != nil { return Account{}, err } return out, refused } // 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 } wantAdmin := pol.isAdmin(u.Email, groups) now := time.Now().UTC().Truncate(time.Second) var out User var refused error err := a.update(func(m map[string]*Account) error { refused = nil var acc *Account for _, c := range m { if c.Provider == ProviderOIDC && c.Sub == u.Sub { acc = c break } } if acc == nil { id := oidcID(u.Email, u.Sub) if _, taken := m[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: now} if wantAdmin || !hasAdmin(m) { acc.Role = RoleAdmin } m[acc.ID] = acc } else { acc.Name, acc.Email = name, u.Email if pol.configured() { switch { case wantAdmin: acc.Role = RoleAdmin case acc.Role == RoleAdmin && otherAdmin(m, acc.ID): acc.Role = RoleUser } } } switch acc.Status { case StatusPending: refused = ErrPending case StatusDisabled: refused = ErrDisabled default: acc.LastLogin = now } out = acc.User() return nil }) if err != nil { return User{}, err } return out, refused } // otherAdmin indique si un administrateur actif autre que id existe dans m. func otherAdmin(m map[string]*Account, id string) bool { for _, acc := range m { 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) } var out Account err := a.update(func(m map[string]*Account) error { acc := m[id] if acc == nil { return ErrNoAccount } next := *acc if p.Name != nil { n, ok := cleanText(*p.Name, maxNameLen) if !ok || n == "" { return 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 fmt.Errorf("%w : adresse e-mail", ErrInvalidAccount) } next.Email = e } if p.Role != nil { if *p.Role != RoleAdmin && *p.Role != RoleUser { return 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 fmt.Errorf("%w : état", ErrInvalidAccount) } next.Status = *p.Status } if p.Password != nil { if next.Provider != ProviderLocal { return 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 && !otherAdmin(m, id) { return ErrLastAdmin } *acc = next out = next return nil }) if err != nil { return Account{}, err } return out, 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 { return a.update(func(m map[string]*Account) error { acc := m[id] if acc == nil { return ErrNoAccount } if acc.Role == RoleAdmin && acc.Status == StatusActive && !otherAdmin(m, id) { return ErrLastAdmin } delete(m, id) 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) }