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) }