Lot 2 (suite) : auth.Accounts sur fichier ou catalogue

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LNfwm4pfYR9C914C2EeiuB
This commit is contained in:
claude BotandClaude Opus 5.5 committed 2026-11-20 17:36:09 +01:00
1 parent 05edcd6b8e
commit 3bbbac5998
1 file changed
+230 -97
+230 -97
View File
@@ -104,14 +104,22 @@ 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} 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. // 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 { type Accounts struct {
mu sync.Mutex mu sync.Mutex
file string file string
byID map[string]*Account 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 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. // OpenAccounts charge (ou crée) le fichier des comptes de dir.
func OpenAccounts(dir string) (*Accounts, error) { func OpenAccounts(dir string) (*Accounts, error) {
a := &Accounts{file: filepath.Join(dir, accountsFile), byID: map[string]*Account{}} a := &Accounts{file: filepath.Join(dir, accountsFile), byID: map[string]*Account{}}
@@ -121,13 +129,11 @@ func OpenAccounts(dir string) (*Accounts, error) {
case err != nil: case err != nil:
return nil, err return nil, err
default: default:
var d struct { list, err := decodeAccounts(b)
Accounts []*Account `json:"accounts"` if err != nil {
}
if err := json.Unmarshal(b, &d); err != nil {
return nil, errors.New(a.file + " invalide : " + err.Error()) return nil, errors.New(a.file + " invalide : " + err.Error())
} }
for _, acc := range d.Accounts { for _, acc := range list {
a.byID[acc.ID] = acc a.byID[acc.ID] = acc
} }
} }
@@ -135,10 +141,88 @@ func OpenAccounts(dir string) (*Accounts, error) {
return a, nil 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. // save écrit le fichier ; appelé sous mu.
func (a *Accounts) save() error { func (a *Accounts) save(m map[string]*Account) error {
list := make([]*Account, 0, len(a.byID)) list := make([]*Account, 0, len(m))
for _, acc := range a.byID { for _, acc := range m {
list = append(list, acc) list = append(list, acc)
} }
sort.Slice(list, func(i, j int) bool { return list[i].Created.Before(list[j].Created) }) sort.Slice(list, func(i, j int) bool { return list[i].Created.Before(list[j].Created) })
@@ -213,6 +297,18 @@ func ValidatePassword(pw string) error {
// Get renvoie le compte d'identifiant id. // Get renvoie le compte d'identifiant id.
func (a *Accounts) Get(id string) (Account, bool) { 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() a.mu.Lock()
defer a.mu.Unlock() defer a.mu.Unlock()
if acc, ok := a.byID[id]; ok { if acc, ok := a.byID[id]; ok {
@@ -221,12 +317,21 @@ func (a *Accounts) Get(id string) (Account, bool) {
return Account{}, false 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. // List renvoie tous les comptes, du plus ancien au plus récent.
func (a *Accounts) List() []AccountInfo { func (a *Accounts) List() []AccountInfo {
a.mu.Lock() m, _ := a.all()
defer a.mu.Unlock() out := make([]AccountInfo, 0, len(m))
out := make([]AccountInfo, 0, len(a.byID)) for _, acc := range m {
for _, acc := range a.byID {
out = append(out, acc.Info()) out = append(out, acc.Info())
} }
sort.Slice(out, func(i, j int) bool { sort.Slice(out, func(i, j int) bool {
@@ -240,14 +345,13 @@ func (a *Accounts) List() []AccountInfo {
// Count renvoie le nombre de comptes. // Count renvoie le nombre de comptes.
func (a *Accounts) Count() int { func (a *Accounts) Count() int {
a.mu.Lock() m, _ := a.all()
defer a.mu.Unlock() return len(m)
return len(a.byID)
} }
// hasAdmin indique si un administrateur actif existe ; appelé sous mu. // hasAdmin indique si un administrateur actif existe dans m.
func (a *Accounts) hasAdmin() bool { func hasAdmin(m map[string]*Account) bool {
for _, acc := range a.byID { for _, acc := range m {
if acc.Role == RoleAdmin && acc.Status == StatusActive { if acc.Role == RoleAdmin && acc.Status == StatusActive {
return true return true
} }
@@ -256,19 +360,17 @@ func (a *Accounts) hasAdmin() bool {
} }
// NeedsSetup indique qu'aucun administrateur n'existe encore : le premier // NeedsSetup indique qu'aucun administrateur n'existe encore : le premier
// compte créé le deviendra. // compte créé le deviendra. Faux si les comptes sont illisibles.
func (a *Accounts) NeedsSetup() bool { func (a *Accounts) NeedsSetup() bool {
a.mu.Lock() m, ok := a.all()
defer a.mu.Unlock() return ok && !hasAdmin(m)
return !a.hasAdmin()
} }
// PendingCount renvoie le nombre d'inscriptions en attente de validation. // PendingCount renvoie le nombre d'inscriptions en attente de validation.
func (a *Accounts) PendingCount() int { func (a *Accounts) PendingCount() int {
a.mu.Lock() m, _ := a.all()
defer a.mu.Unlock()
n := 0 n := 0
for _, acc := range a.byID { for _, acc := range m {
if acc.Status == StatusPending { if acc.Status == StatusPending {
n++ n++
} }
@@ -276,8 +378,8 @@ func (a *Accounts) PendingCount() int {
return n return n
} }
func (a *Accounts) byUsername(name string) *Account { func byUsername(m map[string]*Account, name string) *Account {
for _, acc := range a.byID { for _, acc := range m {
if acc.Provider == ProviderLocal && acc.Username == name { if acc.Provider == ProviderLocal && acc.Username == name {
return acc return acc
} }
@@ -324,15 +426,16 @@ func (a *Accounts) CreateLocal(n NewAccount) (Account, error) {
return Account{}, fmt.Errorf("%w : adresse e-mail", ErrInvalidAccount) return Account{}, fmt.Errorf("%w : adresse e-mail", ErrInvalidAccount)
} }
hash := hashPassword(n.Password) // hors verrou : calcul lent hash := hashPassword(n.Password) // hors verrou : calcul lent
created := time.Now().UTC().Truncate(time.Second)
a.mu.Lock() var out Account
defer a.mu.Unlock() err := a.update(func(m map[string]*Account) error {
if _, exists := a.byID[username]; exists { if _, exists := m[username]; exists {
return Account{}, ErrAccountExists return ErrAccountExists
} }
acc := &Account{ID: username, Username: username, Name: name, Email: email, Provider: ProviderLocal, 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)} Role: n.Role, Status: n.Status, Hash: hash, Created: created}
if !a.hasAdmin() { if !hasAdmin(m) {
acc.Role, acc.Status = RoleAdmin, StatusActive acc.Role, acc.Status = RoleAdmin, StatusActive
} }
if acc.Role != RoleAdmin { if acc.Role != RoleAdmin {
@@ -341,12 +444,14 @@ func (a *Accounts) CreateLocal(n NewAccount) (Account, error) {
if acc.Status != StatusPending && acc.Status != StatusDisabled { if acc.Status != StatusPending && acc.Status != StatusDisabled {
acc.Status = StatusActive acc.Status = StatusActive
} }
a.byID[acc.ID] = acc m[acc.ID] = acc
if err := a.save(); err != nil { out = *acc
delete(a.byID, acc.ID) return nil
})
if err != nil {
return Account{}, err return Account{}, err
} }
return *acc, nil return out, nil
} }
// EnsureAdmin crée l'administrateur local initial (ADMIN_USER / ADMIN_PASSWORD) // EnsureAdmin crée l'administrateur local initial (ADMIN_USER / ADMIN_PASSWORD)
@@ -364,34 +469,56 @@ func (a *Accounts) EnsureAdmin(username, password string) error {
// Authenticate vérifie un identifiant et un mot de passe locaux. // Authenticate vérifie un identifiant et un mot de passe locaux.
func (a *Accounts) Authenticate(username, password string) (Account, error) { func (a *Accounts) Authenticate(username, password string) (Account, error) {
username = strings.ToLower(strings.TrimSpace(username)) username = strings.ToLower(strings.TrimSpace(username))
a.mu.Lock() var acc *Account
acc := a.byUsername(username) if a.db != nil {
var hash string ctx, cancel := context.WithTimeout(context.Background(), accountsTimeout)
if acc != nil { found, err := catalog.FindDoc[Account](ctx, a.db, accountsTable, "username", username)
hash = acc.Hash cancel()
if err != nil {
return Account{}, err
}
if found != nil && found.Provider == ProviderLocal {
acc = found
}
} else { } else {
hash = a.dummy a.mu.Lock()
if p := byUsername(a.byID, username); p != nil {
c := *p
acc = &c
} }
a.mu.Unlock() a.mu.Unlock()
ok := checkPassword(hash, password) && acc != nil }
if !ok { hash := a.dummy
if acc != nil {
hash = acc.Hash
}
if !checkPassword(hash, password) || acc == nil {
return Account{}, ErrBadCredentials return Account{}, ErrBadCredentials
} }
a.mu.Lock() var out Account
defer a.mu.Unlock() var refused error
acc = a.byID[acc.ID] err := a.update(func(m map[string]*Account) error {
if acc == nil { refused = nil
return Account{}, ErrBadCredentials cur := m[acc.ID]
if cur == nil || cur.Hash != hash { // supprimé ou mot de passe changé entre-temps
return ErrBadCredentials
} }
switch acc.Status { out = *cur
switch cur.Status {
case StatusPending: case StatusPending:
return *acc, ErrPending refused = ErrPending
case StatusDisabled: case StatusDisabled:
return *acc, ErrDisabled refused = ErrDisabled
default:
cur.LastLogin = time.Now().UTC().Truncate(time.Second)
out = *cur
} }
acc.LastLogin = time.Now().UTC().Truncate(time.Second) return nil
_ = a.save() })
return *acc, 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 // oidcID construit l'identifiant d'un compte OIDC : l'e-mail s'il existe (il
@@ -458,54 +585,61 @@ func (a *Accounts) UpsertOIDC(u User, groups []string, pol OIDCPolicy) (User, er
if !ok || name == "" { if !ok || name == "" {
name = u.Sub name = u.Sub
} }
a.mu.Lock() wantAdmin := pol.isAdmin(u.Email, groups)
defer a.mu.Unlock() 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 var acc *Account
for _, c := range a.byID { for _, c := range m {
if c.Provider == ProviderOIDC && c.Sub == u.Sub { if c.Provider == ProviderOIDC && c.Sub == u.Sub {
acc = c acc = c
break break
} }
} }
wantAdmin := pol.isAdmin(u.Email, groups)
if acc == nil { if acc == nil {
id := oidcID(u.Email, u.Sub) id := oidcID(u.Email, u.Sub)
if _, taken := a.byID[id]; taken { // même e-mail, autre sujet : identifiant distinct if _, taken := m[id]; taken { // même e-mail, autre sujet : identifiant distinct
id = "oidc." + sanitizeID(u.Sub) id = "oidc." + sanitizeID(u.Sub)
} }
acc = &Account{ID: id, Name: name, Email: u.Email, Provider: ProviderOIDC, Sub: 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)} Role: RoleUser, Status: StatusActive, Created: now}
if wantAdmin || !a.hasAdmin() { if wantAdmin || !hasAdmin(m) {
acc.Role = RoleAdmin acc.Role = RoleAdmin
} }
a.byID[acc.ID] = acc m[acc.ID] = acc
} else { } else {
acc.Name, acc.Email = name, u.Email acc.Name, acc.Email = name, u.Email
if pol.configured() { if pol.configured() {
switch { switch {
case wantAdmin: case wantAdmin:
acc.Role = RoleAdmin acc.Role = RoleAdmin
case acc.Role == RoleAdmin && a.otherAdmin(acc.ID): case acc.Role == RoleAdmin && otherAdmin(m, acc.ID):
acc.Role = RoleUser acc.Role = RoleUser
} }
} }
} }
switch acc.Status { switch acc.Status {
case StatusPending: case StatusPending:
return acc.User(), ErrPending refused = ErrPending
case StatusDisabled: case StatusDisabled:
return acc.User(), ErrDisabled refused = ErrDisabled
default:
acc.LastLogin = now
} }
acc.LastLogin = time.Now().UTC().Truncate(time.Second) out = acc.User()
if err := a.save(); err != nil { return nil
})
if err != nil {
return User{}, err return User{}, err
} }
return acc.User(), nil return out, refused
} }
// otherAdmin indique si un administrateur actif autre que id existe ; appelé sous mu. // otherAdmin indique si un administrateur actif autre que id existe dans m.
func (a *Accounts) otherAdmin(id string) bool { func otherAdmin(m map[string]*Account, id string) bool {
for _, acc := range a.byID { for _, acc := range m {
if acc.ID != id && acc.Role == RoleAdmin && acc.Status == StatusActive { if acc.ID != id && acc.Role == RoleAdmin && acc.Status == StatusActive {
return true return true
} }
@@ -534,55 +668,58 @@ func (a *Accounts) Update(id string, p Patch) (Account, error) {
} }
hash = hashPassword(*p.Password) hash = hashPassword(*p.Password)
} }
a.mu.Lock() var out Account
defer a.mu.Unlock() err := a.update(func(m map[string]*Account) error {
acc := a.byID[id] acc := m[id]
if acc == nil { if acc == nil {
return Account{}, ErrNoAccount return ErrNoAccount
} }
next := *acc next := *acc
if p.Name != nil { if p.Name != nil {
n, ok := cleanText(*p.Name, maxNameLen) n, ok := cleanText(*p.Name, maxNameLen)
if !ok || n == "" { if !ok || n == "" {
return Account{}, fmt.Errorf("%w : nom", ErrInvalidAccount) return fmt.Errorf("%w : nom", ErrInvalidAccount)
} }
next.Name = n next.Name = n
} }
if p.Email != nil && next.Provider == ProviderLocal { if p.Email != nil && next.Provider == ProviderLocal {
e, ok := cleanText(*p.Email, 120) e, ok := cleanText(*p.Email, 120)
if !ok || (e != "" && (!strings.Contains(e, "@") || strings.ContainsAny(e, " <>\"'"))) { if !ok || (e != "" && (!strings.Contains(e, "@") || strings.ContainsAny(e, " <>\"'"))) {
return Account{}, fmt.Errorf("%w : adresse e-mail", ErrInvalidAccount) return fmt.Errorf("%w : adresse e-mail", ErrInvalidAccount)
} }
next.Email = e next.Email = e
} }
if p.Role != nil { if p.Role != nil {
if *p.Role != RoleAdmin && *p.Role != RoleUser { if *p.Role != RoleAdmin && *p.Role != RoleUser {
return Account{}, fmt.Errorf("%w : rôle", ErrInvalidAccount) return fmt.Errorf("%w : rôle", ErrInvalidAccount)
} }
next.Role = *p.Role next.Role = *p.Role
} }
if p.Status != nil { if p.Status != nil {
if *p.Status != StatusActive && *p.Status != StatusPending && *p.Status != StatusDisabled { if *p.Status != StatusActive && *p.Status != StatusPending && *p.Status != StatusDisabled {
return Account{}, fmt.Errorf("%w : état", ErrInvalidAccount) return fmt.Errorf("%w : état", ErrInvalidAccount)
} }
next.Status = *p.Status next.Status = *p.Status
} }
if p.Password != nil { if p.Password != nil {
if next.Provider != ProviderLocal { if next.Provider != ProviderLocal {
return Account{}, fmt.Errorf("%w : mot de passe géré par le fournisseur d'identité", ErrInvalidAccount) return fmt.Errorf("%w : mot de passe géré par le fournisseur d'identité", ErrInvalidAccount)
} }
next.Hash = hash next.Hash = hash
} }
wasAdmin := acc.Role == RoleAdmin && acc.Status == StatusActive wasAdmin := acc.Role == RoleAdmin && acc.Status == StatusActive
isAdmin := next.Role == RoleAdmin && next.Status == StatusActive isAdmin := next.Role == RoleAdmin && next.Status == StatusActive
if wasAdmin && !isAdmin && !a.otherAdmin(id) { if wasAdmin && !isAdmin && !otherAdmin(m, id) {
return Account{}, ErrLastAdmin return ErrLastAdmin
} }
*acc = next *acc = next
if err := a.save(); err != nil { out = next
return nil
})
if err != nil {
return Account{}, err return Account{}, err
} }
return *acc, nil return out, nil
} }
// ChangePassword remplace le mot de passe d'un compte local après vérification // ChangePassword remplace le mot de passe d'un compte local après vérification
@@ -604,21 +741,17 @@ func (a *Accounts) ChangePassword(id, current, next string) error {
// Delete supprime un compte. Le dernier administrateur actif ne peut l'être. // Delete supprime un compte. Le dernier administrateur actif ne peut l'être.
func (a *Accounts) Delete(id string) error { func (a *Accounts) Delete(id string) error {
a.mu.Lock() return a.update(func(m map[string]*Account) error {
defer a.mu.Unlock() acc := m[id]
acc := a.byID[id]
if acc == nil { if acc == nil {
return ErrNoAccount return ErrNoAccount
} }
if acc.Role == RoleAdmin && acc.Status == StatusActive && !a.otherAdmin(id) { if acc.Role == RoleAdmin && acc.Status == StatusActive && !otherAdmin(m, id) {
return ErrLastAdmin return ErrLastAdmin
} }
delete(a.byID, id) delete(m, id)
if err := a.save(); err != nil {
a.byID[id] = acc
return err
}
return nil return nil
})
} }
// --- Limitation des tentatives ------------------------------------------------------------ // --- Limitation des tentatives ------------------------------------------------------------