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
+303 -170
+303 -170
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}
}
// 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 {
mu sync.Mutex
file string
byID map[string]*Account
dummy string // empreinte factice : égalise le temps de réponse d'un identifiant inconnu
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{}}
@@ -121,13 +129,11 @@ func OpenAccounts(dir string) (*Accounts, error) {
case err != nil:
return nil, err
default:
var d struct {
Accounts []*Account `json:"accounts"`
}
if err := json.Unmarshal(b, &d); err != nil {
list, err := decodeAccounts(b)
if err != nil {
return nil, errors.New(a.file + " invalide : " + err.Error())
}
for _, acc := range d.Accounts {
for _, acc := range list {
a.byID[acc.ID] = acc
}
}
@@ -135,10 +141,88 @@ func OpenAccounts(dir string) (*Accounts, error) {
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() error {
list := make([]*Account, 0, len(a.byID))
for _, acc := range a.byID {
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) })
@@ -213,6 +297,18 @@ func ValidatePassword(pw string) error {
// 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 {
@@ -221,12 +317,21 @@ func (a *Accounts) Get(id string) (Account, bool) {
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 {
a.mu.Lock()
defer a.mu.Unlock()
out := make([]AccountInfo, 0, len(a.byID))
for _, acc := range a.byID {
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 {
@@ -240,14 +345,13 @@ func (a *Accounts) List() []AccountInfo {
// Count renvoie le nombre de comptes.
func (a *Accounts) Count() int {
a.mu.Lock()
defer a.mu.Unlock()
return len(a.byID)
m, _ := a.all()
return len(m)
}
// hasAdmin indique si un administrateur actif existe ; appelé sous mu.
func (a *Accounts) hasAdmin() bool {
for _, acc := range a.byID {
// 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
}
@@ -256,19 +360,17 @@ func (a *Accounts) hasAdmin() bool {
}
// 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 {
a.mu.Lock()
defer a.mu.Unlock()
return !a.hasAdmin()
m, ok := a.all()
return ok && !hasAdmin(m)
}
// PendingCount renvoie le nombre d'inscriptions en attente de validation.
func (a *Accounts) PendingCount() int {
a.mu.Lock()
defer a.mu.Unlock()
m, _ := a.all()
n := 0
for _, acc := range a.byID {
for _, acc := range m {
if acc.Status == StatusPending {
n++
}
@@ -276,8 +378,8 @@ func (a *Accounts) PendingCount() int {
return n
}
func (a *Accounts) byUsername(name string) *Account {
for _, acc := range a.byID {
func byUsername(m map[string]*Account, name string) *Account {
for _, acc := range m {
if acc.Provider == ProviderLocal && acc.Username == name {
return acc
}
@@ -324,29 +426,32 @@ func (a *Accounts) CreateLocal(n NewAccount) (Account, error) {
return Account{}, fmt.Errorf("%w : adresse e-mail", ErrInvalidAccount)
}
hash := hashPassword(n.Password) // hors verrou : calcul lent
created := time.Now().UTC().Truncate(time.Second)
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)
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 *acc, nil
return out, nil
}
// 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.
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
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
} else {
hash = a.dummy
}
a.mu.Unlock()
ok := checkPassword(hash, password) && acc != nil
if !ok {
if !checkPassword(hash, password) || acc == nil {
return Account{}, ErrBadCredentials
}
a.mu.Lock()
defer a.mu.Unlock()
acc = a.byID[acc.ID]
if 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
}
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
return out, refused
}
// 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 == "" {
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
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
}
}
}
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 {
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 acc.User(), nil
return out, refused
}
// 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 {
// 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
}
@@ -534,55 +668,58 @@ func (a *Accounts) Update(id string, p Patch) (Account, error) {
}
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)
var out Account
err := a.update(func(m map[string]*Account) error {
acc := m[id]
if acc == nil {
return ErrNoAccount
}
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 := *acc
if p.Name != nil {
n, ok := cleanText(*p.Name, maxNameLen)
if !ok || n == "" {
return fmt.Errorf("%w : nom", ErrInvalidAccount)
}
next.Name = n
}
next.Email = e
}
if p.Role != nil {
if *p.Role != RoleAdmin && *p.Role != RoleUser {
return Account{}, fmt.Errorf("%w : rôle", ErrInvalidAccount)
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
}
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)
if p.Role != nil {
if *p.Role != RoleAdmin && *p.Role != RoleUser {
return fmt.Errorf("%w : rôle", ErrInvalidAccount)
}
next.Role = *p.Role
}
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)
if p.Status != nil {
if *p.Status != StatusActive && *p.Status != StatusPending && *p.Status != StatusDisabled {
return fmt.Errorf("%w : état", ErrInvalidAccount)
}
next.Status = *p.Status
}
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 {
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 *acc, nil
return out, nil
}
// 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.
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
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 ------------------------------------------------------------