Up And Down : première version
This commit is contained in:
commit
89c5430308
76 files changed
+20730
No files matched your search
@@ -0,0 +1,677 @@
|
||||
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)
|
||||
}
|
||||
@@ -0,0 +1,473 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/cookiejar"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func init() { pbkdf2Iter = 1000 } // tests rapides
|
||||
|
||||
func newAccounts(t *testing.T) *Accounts {
|
||||
t.Helper()
|
||||
a, err := OpenAccounts(t.TempDir())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return a
|
||||
}
|
||||
|
||||
func TestFirstAccountIsAdmin(t *testing.T) {
|
||||
a := newAccounts(t)
|
||||
if !a.NeedsSetup() {
|
||||
t.Fatal("NeedsSetup")
|
||||
}
|
||||
first, err := a.CreateLocal(NewAccount{Username: "Alice", Password: "un-mot-de-passe", Status: StatusPending})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if first.Role != RoleAdmin || first.Status != StatusActive || first.ID != "alice" {
|
||||
t.Errorf("premier compte = %+v", first)
|
||||
}
|
||||
second, _ := a.CreateLocal(NewAccount{Username: "bob", Password: "un-mot-de-passe", Status: StatusPending})
|
||||
if second.Role != RoleUser || second.Status != StatusPending {
|
||||
t.Errorf("second compte = %+v", second)
|
||||
}
|
||||
if a.NeedsSetup() || a.PendingCount() != 1 {
|
||||
t.Error("état après création")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateLocalValidation(t *testing.T) {
|
||||
a := newAccounts(t)
|
||||
for _, n := range []NewAccount{
|
||||
{Username: "ab", Password: "un-mot-de-passe"}, // trop court
|
||||
{Username: "Bob Dupont", Password: "un-mot-de-passe"}, // espace
|
||||
{Username: "oidc.x", Password: "un-mot-de-passe"}, // préfixe réservé
|
||||
{Username: "bob@example.org", Password: "un-mot-de-passe"}, // @ réservé aux comptes OIDC
|
||||
{Username: "bob", Password: "court"}, // mot de passe trop court
|
||||
{Username: "bob", Password: "un-mot-de-passe", Email: "x"}, // e-mail invalide
|
||||
{Username: "bob", Password: strings.Repeat("x", 300)}, // mot de passe trop long
|
||||
{Username: ".hidden", Password: "un-mot-de-passe"}, // caché
|
||||
{Username: "bob", Password: "un-mot-de-passe", Name: "a\x00"}, // nom invalide
|
||||
} {
|
||||
if _, err := a.CreateLocal(n); !errors.Is(err, ErrInvalidAccount) {
|
||||
t.Errorf("CreateLocal(%+v) = %v", n, err)
|
||||
}
|
||||
}
|
||||
if _, err := a.CreateLocal(NewAccount{Username: "bob", Password: "un-mot-de-passe"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := a.CreateLocal(NewAccount{Username: "BOB", Password: "un-mot-de-passe"}); !errors.Is(err, ErrAccountExists) {
|
||||
t.Errorf("doublon : %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthenticate(t *testing.T) {
|
||||
a := newAccounts(t)
|
||||
_, _ = a.CreateLocal(NewAccount{Username: "alice", Password: "mot-de-passe-1"})
|
||||
_, _ = a.CreateLocal(NewAccount{Username: "bob", Password: "mot-de-passe-2", Status: StatusPending})
|
||||
if _, err := a.Authenticate("Alice", "mot-de-passe-1"); err != nil {
|
||||
t.Errorf("connexion : %v", err)
|
||||
}
|
||||
if _, err := a.Authenticate("alice", "faux"); !errors.Is(err, ErrBadCredentials) {
|
||||
t.Errorf("mauvais mot de passe : %v", err)
|
||||
}
|
||||
if _, err := a.Authenticate("inconnu", "mot-de-passe-1"); !errors.Is(err, ErrBadCredentials) {
|
||||
t.Errorf("inconnu : %v", err)
|
||||
}
|
||||
if _, err := a.Authenticate("bob", "mot-de-passe-2"); !errors.Is(err, ErrPending) {
|
||||
t.Errorf("en attente : %v", err)
|
||||
}
|
||||
// Mauvais mot de passe d'un compte en attente : pas de fuite d'état.
|
||||
if _, err := a.Authenticate("bob", "faux"); !errors.Is(err, ErrBadCredentials) {
|
||||
t.Errorf("fuite d'état : %v", err)
|
||||
}
|
||||
disabled := StatusDisabled
|
||||
_, _ = a.Update("bob", Patch{Status: &disabled})
|
||||
if _, err := a.Authenticate("bob", "mot-de-passe-2"); !errors.Is(err, ErrDisabled) {
|
||||
t.Errorf("désactivé : %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPersistenceAndFileMode(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
a, _ := OpenAccounts(dir)
|
||||
_, _ = a.CreateLocal(NewAccount{Username: "alice", Password: "mot-de-passe-1"})
|
||||
b, err := OpenAccounts(dir)
|
||||
if err != nil || b.Count() != 1 {
|
||||
t.Fatalf("rechargement : %v %d", err, b.Count())
|
||||
}
|
||||
if _, err := b.Authenticate("alice", "mot-de-passe-1"); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLastAdminProtected(t *testing.T) {
|
||||
a := newAccounts(t)
|
||||
_, _ = a.CreateLocal(NewAccount{Username: "alice", Password: "mot-de-passe-1"}) // admin
|
||||
user, disabled := RoleUser, StatusDisabled
|
||||
if _, err := a.Update("alice", Patch{Role: &user}); !errors.Is(err, ErrLastAdmin) {
|
||||
t.Errorf("rétrogradation : %v", err)
|
||||
}
|
||||
if _, err := a.Update("alice", Patch{Status: &disabled}); !errors.Is(err, ErrLastAdmin) {
|
||||
t.Errorf("désactivation : %v", err)
|
||||
}
|
||||
if err := a.Delete("alice"); !errors.Is(err, ErrLastAdmin) {
|
||||
t.Errorf("suppression : %v", err)
|
||||
}
|
||||
admin := RoleAdmin
|
||||
_, _ = a.CreateLocal(NewAccount{Username: "bob", Password: "mot-de-passe-2"})
|
||||
_, _ = a.Update("bob", Patch{Role: &admin})
|
||||
if _, err := a.Update("alice", Patch{Role: &user}); err != nil {
|
||||
t.Errorf("rétrogradation avec un autre admin : %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChangePassword(t *testing.T) {
|
||||
a := newAccounts(t)
|
||||
_, _ = a.CreateLocal(NewAccount{Username: "alice", Password: "ancien-mot-de-passe"})
|
||||
if err := a.ChangePassword("alice", "faux", "nouveau-mot-de-passe"); !errors.Is(err, ErrBadCredentials) {
|
||||
t.Errorf("ancien faux : %v", err)
|
||||
}
|
||||
if err := a.ChangePassword("alice", "ancien-mot-de-passe", "court"); !errors.Is(err, ErrInvalidAccount) {
|
||||
t.Errorf("nouveau trop court : %v", err)
|
||||
}
|
||||
if err := a.ChangePassword("alice", "ancien-mot-de-passe", "nouveau-mot-de-passe"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := a.Authenticate("alice", "nouveau-mot-de-passe"); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
if _, err := a.Authenticate("alice", "ancien-mot-de-passe"); err == nil {
|
||||
t.Error("ancien mot de passe encore valable")
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpsertOIDC(t *testing.T) {
|
||||
a := newAccounts(t)
|
||||
pol := OIDCPolicy{AdminGroups: []string{"admins"}}
|
||||
u1, err := a.UpsertOIDC(User{Sub: "s1", Name: "Zoé", Email: "Zoe@Example.org"}, []string{"users"}, pol)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Premier compte : administrateur même hors du groupe (aucun admin n'existait).
|
||||
if u1.ID != "zoe@example.org" || u1.Role != RoleAdmin || u1.Provider != ProviderOIDC {
|
||||
t.Errorf("premier = %+v", u1)
|
||||
}
|
||||
u2, _ := a.UpsertOIDC(User{Sub: "s2", Name: "Max", Email: "max@example.org"}, []string{"users"}, pol)
|
||||
if u2.Role != RoleUser {
|
||||
t.Errorf("second = %+v", u2)
|
||||
}
|
||||
// Promotion par groupe, puis rétrogradation quand il en sort.
|
||||
u2, _ = a.UpsertOIDC(User{Sub: "s2", Name: "Max", Email: "max@example.org"}, []string{"admins"}, pol)
|
||||
if u2.Role != RoleAdmin {
|
||||
t.Errorf("promotion = %+v", u2)
|
||||
}
|
||||
u2, _ = a.UpsertOIDC(User{Sub: "s2", Name: "Max", Email: "max@example.org"}, nil, pol)
|
||||
if u2.Role != RoleUser {
|
||||
t.Errorf("rétrogradation = %+v", u2)
|
||||
}
|
||||
// Même sujet, nouvel e-mail : même compte.
|
||||
u3, _ := a.UpsertOIDC(User{Sub: "s2", Name: "Max B", Email: "max@autre.org"}, nil, pol)
|
||||
if u3.ID != u2.ID || u3.Name != "Max B" {
|
||||
t.Errorf("identité : %+v", u3)
|
||||
}
|
||||
// Sans e-mail : identifiant « oidc.<sub> », qui ne peut pas être un identifiant local.
|
||||
u4, _ := a.UpsertOIDC(User{Sub: "S/4", Name: "Sans mail"}, nil, pol)
|
||||
if !strings.HasPrefix(u4.ID, "oidc.") {
|
||||
t.Errorf("sans e-mail = %+v", u4)
|
||||
}
|
||||
if _, err := a.CreateLocal(NewAccount{Username: u4.ID, Password: "mot-de-passe-1"}); err == nil {
|
||||
t.Error("identifiant local en collision avec un compte OIDC")
|
||||
}
|
||||
// Même e-mail, autre sujet : pas de fusion (prise de contrôle).
|
||||
u5, _ := a.UpsertOIDC(User{Sub: "autre", Name: "Usurpateur", Email: "zoe@example.org"}, nil, pol)
|
||||
if u5.ID == u1.ID {
|
||||
t.Error("deux sujets OIDC partagent un compte")
|
||||
}
|
||||
// Désactivation.
|
||||
disabled := StatusDisabled
|
||||
_, _ = a.Update(u2.ID, Patch{Status: &disabled})
|
||||
if _, err := a.UpsertOIDC(User{Sub: "s2", Name: "Max", Email: "max@autre.org"}, nil, pol); !errors.Is(err, ErrDisabled) {
|
||||
t.Errorf("désactivé : %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLimiter(t *testing.T) {
|
||||
l := NewLimiter(3, 50*time.Millisecond)
|
||||
for i := 0; i < 3; i++ {
|
||||
if !l.Allowed("k") {
|
||||
t.Fatal("bloqué trop tôt")
|
||||
}
|
||||
l.Fail("k")
|
||||
}
|
||||
if l.Allowed("k") {
|
||||
t.Error("pas bloqué")
|
||||
}
|
||||
if !l.Allowed("autre") {
|
||||
t.Error("autre clé bloquée")
|
||||
}
|
||||
time.Sleep(60 * time.Millisecond)
|
||||
if !l.Allowed("k") {
|
||||
t.Error("fenêtre non expirée")
|
||||
}
|
||||
l.Fail("k")
|
||||
l.Reset("k")
|
||||
if !l.Allowed("k") {
|
||||
t.Error("Reset")
|
||||
}
|
||||
}
|
||||
|
||||
// --- Flux HTTP (sans ouvrir de port) -------------------------------------------------
|
||||
|
||||
type browser struct {
|
||||
t *testing.T
|
||||
h http.Handler
|
||||
cookies map[string]*http.Cookie
|
||||
}
|
||||
|
||||
func newBrowser(t *testing.T, h http.Handler) *browser {
|
||||
return &browser{t: t, h: h, cookies: map[string]*http.Cookie{}}
|
||||
}
|
||||
|
||||
func (b *browser) do(method, path, body string) *httptest.ResponseRecorder {
|
||||
r := httptest.NewRequest(method, path, strings.NewReader(body))
|
||||
if body != "" {
|
||||
r.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
for _, c := range b.cookies {
|
||||
r.AddCookie(c)
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
b.h.ServeHTTP(w, r)
|
||||
for _, c := range w.Result().Cookies() {
|
||||
if c.MaxAge < 0 {
|
||||
delete(b.cookies, c.Name)
|
||||
} else {
|
||||
b.cookies[c.Name] = c
|
||||
}
|
||||
}
|
||||
return w
|
||||
}
|
||||
|
||||
func testAuth(t *testing.T, reg string) (*Auth, http.Handler) {
|
||||
t.Helper()
|
||||
acc := newAccounts(t)
|
||||
a := New(&Auth{
|
||||
Accounts: acc,
|
||||
Sessions: NewSessions([]byte("0123456789abcdef0123456789abcdef"), time.Hour, false),
|
||||
Local: true,
|
||||
Registration: func() string { return reg },
|
||||
})
|
||||
mux := http.NewServeMux()
|
||||
a.Register(mux)
|
||||
mux.HandleFunc("GET /api/whoami", func(w http.ResponseWriter, r *http.Request) {
|
||||
u := UserFrom(r.Context())
|
||||
_, _ = w.Write([]byte(u.ID + ":" + u.Role))
|
||||
})
|
||||
mux.HandleFunc("GET /api/open", func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte("ouvert")) })
|
||||
mux.HandleFunc("GET /", func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte("<html>spa</html>")) })
|
||||
return a, a.Middleware(mux, func(p string) bool { return p == "/api/open" })
|
||||
}
|
||||
|
||||
func TestRegistrationClosedAllowsOnlySetup(t *testing.T) {
|
||||
_, h := testAuth(t, "closed")
|
||||
b := newBrowser(t, h)
|
||||
// Premier compte : accepté malgré « closed » (installation), connecté d'office.
|
||||
w := b.do("POST", "/auth/local/register", `{"username":"admin","password":"mot-de-passe-1"}`)
|
||||
if w.Code != 201 {
|
||||
t.Fatalf("installation : %d %s", w.Code, w.Body)
|
||||
}
|
||||
if got := b.do("GET", "/api/whoami", "").Body.String(); got != "admin:admin" {
|
||||
t.Errorf("whoami = %q", got)
|
||||
}
|
||||
// Ensuite, fermé.
|
||||
b2 := newBrowser(t, h)
|
||||
if w := b2.do("POST", "/auth/local/register", `{"username":"bob","password":"mot-de-passe-1"}`); w.Code != 403 {
|
||||
t.Errorf("inscription fermée : %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistrationApprovalFlow(t *testing.T) {
|
||||
a, h := testAuth(t, "approval")
|
||||
_, _ = a.Accounts.CreateLocal(NewAccount{Username: "root", Password: "mot-de-passe-0"})
|
||||
b := newBrowser(t, h)
|
||||
w := b.do("POST", "/auth/local/register", `{"username":"bob","name":"Bob","password":"mot-de-passe-1"}`)
|
||||
if w.Code != 202 || len(b.cookies) != 0 {
|
||||
t.Fatalf("inscription : %d %s %v", w.Code, w.Body, b.cookies)
|
||||
}
|
||||
w = b.do("POST", "/auth/local/login", `{"username":"bob","password":"mot-de-passe-1"}`)
|
||||
if w.Code != 403 || !strings.Contains(w.Body.String(), `"pending"`) {
|
||||
t.Errorf("connexion en attente : %d %s", w.Code, w.Body)
|
||||
}
|
||||
if b.do("GET", "/api/whoami", "").Code != 401 {
|
||||
t.Error("accès sans session")
|
||||
}
|
||||
active := StatusActive
|
||||
_, _ = a.Accounts.Update("bob", Patch{Status: &active})
|
||||
if w = b.do("POST", "/auth/local/login", `{"username":"bob","password":"mot-de-passe-1"}`); w.Code != 200 {
|
||||
t.Fatalf("connexion : %d %s", w.Code, w.Body)
|
||||
}
|
||||
if got := b.do("GET", "/api/whoami", "").Body.String(); got != "bob:user" {
|
||||
t.Errorf("whoami = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistrationOpenAutoLogin(t *testing.T) {
|
||||
a, h := testAuth(t, "open")
|
||||
_, _ = a.Accounts.CreateLocal(NewAccount{Username: "root", Password: "mot-de-passe-0"})
|
||||
b := newBrowser(t, h)
|
||||
if w := b.do("POST", "/auth/local/register", `{"username":"carl","password":"mot-de-passe-1"}`); w.Code != 201 {
|
||||
t.Fatalf("%d %s", w.Code, w.Body)
|
||||
}
|
||||
if got := b.do("GET", "/api/whoami", "").Body.String(); got != "carl:user" {
|
||||
t.Errorf("whoami = %q", got)
|
||||
}
|
||||
if w := b.do("POST", "/auth/local/register", `{"username":"carl","password":"mot-de-passe-1"}`); w.Code != 409 {
|
||||
t.Errorf("doublon : %d", w.Code)
|
||||
}
|
||||
if w := b.do("POST", "/auth/local/register", `{"username":"x","password":"mot-de-passe-1"}`); w.Code != 400 {
|
||||
t.Errorf("identifiant invalide : %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistrationThrottle(t *testing.T) {
|
||||
a, h := testAuth(t, "open")
|
||||
_, _ = a.Accounts.CreateLocal(NewAccount{Username: "root", Password: "mot-de-passe-0"})
|
||||
last := 0
|
||||
for i := 0; i < 8; i++ {
|
||||
b := newBrowser(t, h)
|
||||
w := b.do("POST", "/auth/local/register", `{"username":"user`+string(rune('a'+i))+`x","password":"mot-de-passe-1"}`)
|
||||
last = w.Code
|
||||
}
|
||||
if last != 429 {
|
||||
t.Errorf("après 8 inscriptions depuis la même adresse : %d", last)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoginThrottleAndSessionRules(t *testing.T) {
|
||||
a, h := testAuth(t, "closed")
|
||||
_, _ = a.Accounts.CreateLocal(NewAccount{Username: "alice", Password: "mot-de-passe-1"})
|
||||
b := newBrowser(t, h)
|
||||
for i := 0; i < 10; i++ {
|
||||
if w := b.do("POST", "/auth/local/login", `{"username":"alice","password":"faux"}`); w.Code != 401 {
|
||||
t.Fatalf("essai %d : %d", i, w.Code)
|
||||
}
|
||||
}
|
||||
if w := b.do("POST", "/auth/local/login", `{"username":"alice","password":"mot-de-passe-1"}`); w.Code != 429 {
|
||||
t.Errorf("après 10 échecs : %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMiddlewareRoutesAndSessionRevocation(t *testing.T) {
|
||||
a, h := testAuth(t, "closed")
|
||||
_, _ = a.Accounts.CreateLocal(NewAccount{Username: "alice", Password: "mot-de-passe-1"})
|
||||
_, _ = a.Accounts.CreateLocal(NewAccount{Username: "bob", Password: "mot-de-passe-2"})
|
||||
b := newBrowser(t, h)
|
||||
// Sans session : API refusée, route publique ouverte, navigation = application.
|
||||
if w := b.do("GET", "/api/whoami", ""); w.Code != 401 || w.Header().Get(LoginHeader) != "" {
|
||||
t.Errorf("API : %d %v", w.Code, w.Header())
|
||||
}
|
||||
if w := b.do("GET", "/api/open", ""); w.Code != 200 {
|
||||
t.Errorf("public : %d", w.Code)
|
||||
}
|
||||
if w := b.do("GET", "/", ""); w.Code != 200 || !strings.Contains(w.Body.String(), "spa") {
|
||||
t.Errorf("navigation : %d %s", w.Code, w.Body)
|
||||
}
|
||||
if w := b.do("POST", "/api/whoami", ""); w.Code != 401 {
|
||||
t.Errorf("POST sans session : %d", w.Code)
|
||||
}
|
||||
b.do("POST", "/auth/local/login", `{"username":"bob","password":"mot-de-passe-2"}`)
|
||||
if got := b.do("GET", "/api/whoami", "").Body.String(); got != "bob:user" {
|
||||
t.Fatalf("whoami = %q", got)
|
||||
}
|
||||
// Un compte désactivé perd sa session tout de suite.
|
||||
disabled := StatusDisabled
|
||||
_, _ = a.Accounts.Update("bob", Patch{Status: &disabled})
|
||||
if w := b.do("GET", "/api/whoami", ""); w.Code != 401 {
|
||||
t.Errorf("session d'un compte désactivé : %d", w.Code)
|
||||
}
|
||||
// Un compte supprimé aussi.
|
||||
b2 := newBrowser(t, h)
|
||||
b2.do("POST", "/auth/local/login", `{"username":"alice","password":"mot-de-passe-1"}`)
|
||||
_, _ = a.Accounts.CreateLocal(NewAccount{Username: "carl", Password: "mot-de-passe-3", Role: RoleAdmin})
|
||||
_ = a.Accounts.Delete("alice")
|
||||
if w := b2.do("GET", "/api/whoami", ""); w.Code != 401 {
|
||||
t.Errorf("session d'un compte supprimé : %d", w.Code)
|
||||
}
|
||||
// Un cookie falsifié est refusé.
|
||||
b3 := newBrowser(t, h)
|
||||
b3.cookies["upandown_session"] = &http.Cookie{Name: "upandown_session", Value: "eyJpZCI6ImFkbWluIn0.AAAA"}
|
||||
if w := b3.do("GET", "/api/whoami", ""); w.Code != 401 {
|
||||
t.Errorf("cookie falsifié : %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLogoutClearsSession(t *testing.T) {
|
||||
a, h := testAuth(t, "closed")
|
||||
_, _ = a.Accounts.CreateLocal(NewAccount{Username: "alice", Password: "mot-de-passe-1"})
|
||||
b := newBrowser(t, h)
|
||||
b.do("POST", "/auth/local/login", `{"username":"alice","password":"mot-de-passe-1"}`)
|
||||
if w := b.do("GET", "/auth/logout", ""); w.Code != 303 {
|
||||
t.Errorf("logout : %d", w.Code)
|
||||
}
|
||||
if w := b.do("GET", "/api/whoami", ""); w.Code != 401 {
|
||||
t.Errorf("après logout : %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOIDCLoginCreatesAccountAndHonoursStatus(t *testing.T) {
|
||||
idp := newIdP(t, "RS256")
|
||||
acc := newAccounts(t)
|
||||
sessions := NewSessions([]byte("0123456789abcdef0123456789abcdef"), time.Hour, false)
|
||||
o, err := NewOIDC(context.Background(), Config{
|
||||
Issuer: idp.srv.URL, ClientID: "excalicloud", ClientSecret: idp.secret,
|
||||
Secret: []byte("0123456789abcdef0123456789abcdef"), Client: testNet.client(), Sessions: sessions,
|
||||
Provision: func(u User, g []string) (User, error) { return acc.UpsertOIDC(u, g, OIDCPolicy{}) },
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
a := New(&Auth{Accounts: acc, Sessions: sessions, OIDC: o})
|
||||
mux := http.NewServeMux()
|
||||
a.Register(mux)
|
||||
mux.HandleFunc("GET /api/whoami", func(w http.ResponseWriter, r *http.Request) {
|
||||
u := UserFrom(r.Context())
|
||||
_, _ = w.Write([]byte(u.ID + ":" + u.Role + ":" + u.Provider))
|
||||
})
|
||||
mux.HandleFunc("GET /", func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte("app")) })
|
||||
srv := testNet.serve("app", a.Middleware(mux, func(string) bool { return false }))
|
||||
jar, _ := cookiejar.New(nil)
|
||||
c := &http.Client{Jar: jar, Transport: testNet}
|
||||
|
||||
if res, body := get(t, c, srv.URL+"/api/whoami"); res.StatusCode != 401 || res.Header.Get(LoginHeader) != "/auth/login" {
|
||||
t.Fatalf("OIDC seul, sans session : %d %q", res.StatusCode, body)
|
||||
}
|
||||
if res, body := get(t, c, srv.URL+"/auth/login"); res.StatusCode != 200 || body != "app" {
|
||||
t.Fatalf("connexion : %d %q", res.StatusCode, body)
|
||||
}
|
||||
if _, body := get(t, c, srv.URL+"/api/whoami"); body != "cedric@example.org:admin:oidc" {
|
||||
t.Errorf("whoami = %q", body)
|
||||
}
|
||||
if got, ok := acc.Get("cedric@example.org"); !ok || got.Sub != "u-42" {
|
||||
t.Errorf("compte non créé : %+v", got)
|
||||
}
|
||||
// Désactivation : la session tombe, la reconnexion est refusée avec un message clair.
|
||||
id := "cedric@example.org"
|
||||
admin, disabled := RoleAdmin, StatusDisabled
|
||||
_, _ = acc.CreateLocal(NewAccount{Username: "backup", Password: "mot-de-passe-1", Role: admin})
|
||||
_, _ = acc.Update(id, Patch{Status: &disabled})
|
||||
if res, _ := get(t, c, srv.URL+"/api/whoami"); res.StatusCode != 401 {
|
||||
t.Errorf("session d'un compte désactivé : %d", res.StatusCode)
|
||||
}
|
||||
res, body := get(t, c, srv.URL+"/auth/login")
|
||||
if res.StatusCode != 403 || !strings.Contains(body, "désactivé") {
|
||||
t.Errorf("reconnexion refusée : %d %.80s", res.StatusCode, body)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Auth réunit l'authentification locale (comptes, inscription) et OIDC derrière
|
||||
// une même session : cookie signé, vérifié à chaque requête contre l'état du
|
||||
// compte (désactivé, supprimé, rôle modifié : effet immédiat).
|
||||
//
|
||||
// POST /auth/local/login {"username","password"}
|
||||
// POST /auth/local/register {"username","name","email","password"}
|
||||
// GET /auth/login connexion OIDC (si activée)
|
||||
// GET /auth/logout déconnexion (propagée au fournisseur OIDC)
|
||||
type Auth struct {
|
||||
Accounts *Accounts
|
||||
Sessions *Sessions
|
||||
OIDC *OIDC // nil : OIDC désactivé
|
||||
Local bool // comptes locaux activés
|
||||
// Registration renvoie le mode d'inscription courant : closed, approval ou open.
|
||||
Registration func() string
|
||||
// OIDCName : libellé du bouton de connexion OIDC.
|
||||
OIDCName string
|
||||
|
||||
logins *Limiter
|
||||
regs *Limiter
|
||||
}
|
||||
|
||||
// New prépare l'authentification ; Accounts et Sessions sont obligatoires.
|
||||
func New(a *Auth) *Auth {
|
||||
a.logins = NewLimiter(10, 15*time.Minute)
|
||||
a.regs = NewLimiter(5, time.Hour)
|
||||
if a.Registration == nil {
|
||||
a.Registration = func() string { return "closed" }
|
||||
}
|
||||
return a
|
||||
}
|
||||
|
||||
// OnlyOIDC indique que la connexion passe uniquement par le fournisseur OIDC.
|
||||
func (a *Auth) OnlyOIDC() bool { return a.OIDC != nil && !a.Local }
|
||||
|
||||
// Register ajoute les routes /auth/*.
|
||||
func (a *Auth) Register(mux *http.ServeMux) {
|
||||
if a.OIDC != nil {
|
||||
a.OIDC.RegisterLogin(mux)
|
||||
}
|
||||
if a.Local {
|
||||
mux.HandleFunc("POST /auth/local/login", a.localLogin)
|
||||
mux.HandleFunc("POST /auth/local/register", a.localRegister)
|
||||
}
|
||||
mux.HandleFunc("GET /auth/logout", a.logout)
|
||||
mux.HandleFunc("POST /auth/logout", a.logout)
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, status int, v any) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(v)
|
||||
}
|
||||
|
||||
func writeErr(w http.ResponseWriter, status int, msg string) {
|
||||
writeJSON(w, status, map[string]string{"error": msg})
|
||||
}
|
||||
|
||||
// clientIP : adresse du client. Derrière un reverse proxy, l'entrée la plus à
|
||||
// droite de X-Forwarded-For est celle qu'il a ajoutée.
|
||||
func clientIP(r *http.Request) string {
|
||||
if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
|
||||
parts := strings.Split(xff, ",")
|
||||
if ip := strings.TrimSpace(parts[len(parts)-1]); ip != "" {
|
||||
return ip
|
||||
}
|
||||
}
|
||||
host, _, err := net.SplitHostPort(r.RemoteAddr)
|
||||
if err != nil {
|
||||
return r.RemoteAddr
|
||||
}
|
||||
return host
|
||||
}
|
||||
|
||||
type credentials struct {
|
||||
Username string `json:"username"`
|
||||
Name string `json:"name"`
|
||||
Email string `json:"email"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
func decodeJSON(w http.ResponseWriter, r *http.Request, v any) bool {
|
||||
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 16<<10)).Decode(v); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "requête JSON invalide")
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (a *Auth) localLogin(w http.ResponseWriter, r *http.Request) {
|
||||
var c credentials
|
||||
if !decodeJSON(w, r, &c) {
|
||||
return
|
||||
}
|
||||
userKey, ipKey := "u:"+strings.ToLower(strings.TrimSpace(c.Username)), "ip:"+clientIP(r)
|
||||
if !a.logins.Allowed(userKey) || !a.logins.Allowed(ipKey) {
|
||||
w.Header().Set("Retry-After", "900")
|
||||
writeErr(w, http.StatusTooManyRequests, "trop de tentatives : réessayer dans quelques minutes")
|
||||
return
|
||||
}
|
||||
acc, err := a.Accounts.Authenticate(c.Username, c.Password)
|
||||
switch err {
|
||||
case nil:
|
||||
case ErrBadCredentials:
|
||||
a.logins.Fail(userKey)
|
||||
a.logins.Fail(ipKey)
|
||||
writeErr(w, http.StatusUnauthorized, err.Error())
|
||||
return
|
||||
case ErrPending, ErrDisabled:
|
||||
writeJSON(w, http.StatusForbidden, map[string]string{"error": err.Error(), "code": codeOf(err)})
|
||||
return
|
||||
default:
|
||||
slog.Error("connexion locale", "err", err)
|
||||
writeErr(w, http.StatusInternalServerError, "erreur interne")
|
||||
return
|
||||
}
|
||||
a.logins.Reset(userKey)
|
||||
if err := a.Sessions.Start(w, r, acc.User()); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "erreur interne")
|
||||
return
|
||||
}
|
||||
slog.Info("connexion locale", "user", acc.ID)
|
||||
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
|
||||
}
|
||||
|
||||
func codeOf(err error) string {
|
||||
if err == ErrPending {
|
||||
return "pending"
|
||||
}
|
||||
return "disabled"
|
||||
}
|
||||
|
||||
func (a *Auth) localRegister(w http.ResponseWriter, r *http.Request) {
|
||||
var c credentials
|
||||
if !decodeJSON(w, r, &c) {
|
||||
return
|
||||
}
|
||||
setup := a.Accounts.NeedsSetup() // premier compte : administrateur, même si les inscriptions sont fermées
|
||||
mode := a.Registration()
|
||||
if mode == "closed" && !setup {
|
||||
writeErr(w, http.StatusForbidden, "les inscriptions sont fermées")
|
||||
return
|
||||
}
|
||||
ipKey := "reg:" + clientIP(r)
|
||||
if !setup && !a.regs.Allowed(ipKey) {
|
||||
w.Header().Set("Retry-After", "3600")
|
||||
writeErr(w, http.StatusTooManyRequests, "trop d'inscriptions depuis cette adresse")
|
||||
return
|
||||
}
|
||||
status := StatusActive
|
||||
if mode == "approval" {
|
||||
status = StatusPending
|
||||
}
|
||||
acc, err := a.Accounts.CreateLocal(NewAccount{Username: c.Username, Name: c.Name, Email: c.Email,
|
||||
Password: c.Password, Status: status})
|
||||
if err != nil {
|
||||
code := http.StatusBadRequest
|
||||
if err == ErrAccountExists {
|
||||
code = http.StatusConflict
|
||||
}
|
||||
writeErr(w, code, err.Error())
|
||||
return
|
||||
}
|
||||
if !setup {
|
||||
a.regs.Fail(ipKey)
|
||||
}
|
||||
slog.Info("inscription", "user", acc.ID, "status", acc.Status, "role", acc.Role)
|
||||
if acc.Status == StatusPending {
|
||||
writeJSON(w, http.StatusAccepted, map[string]string{"status": StatusPending})
|
||||
return
|
||||
}
|
||||
if err := a.Sessions.Start(w, r, acc.User()); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "erreur interne")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, map[string]string{"status": StatusActive})
|
||||
}
|
||||
|
||||
func (a *Auth) logout(w http.ResponseWriter, r *http.Request) {
|
||||
if s, ok := a.Sessions.Get(r); ok && s.Provider == ProviderOIDC && a.OIDC != nil {
|
||||
a.OIDC.logout(w, r)
|
||||
return
|
||||
}
|
||||
a.Sessions.Clear(w, r)
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
http.Redirect(w, r, "/", http.StatusSeeOther)
|
||||
}
|
||||
|
||||
// current renvoie l'utilisateur de la session : le compte doit exister et être
|
||||
// actif ; son rôle est celui du compte. La session est prolongée passée la
|
||||
// moitié de sa durée.
|
||||
func (a *Auth) current(w http.ResponseWriter, r *http.Request) (*User, bool) {
|
||||
s, ok := a.Sessions.Get(r)
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
acc, ok := a.Accounts.Get(s.ID)
|
||||
if !ok || acc.Status != StatusActive {
|
||||
a.Sessions.Clear(w, r)
|
||||
return nil, false
|
||||
}
|
||||
u := acc.User()
|
||||
if time.Until(time.Unix(s.Exp, 0)) < a.Sessions.TTL/2 {
|
||||
_ = a.Sessions.Start(w, r, u)
|
||||
}
|
||||
return &u, true
|
||||
}
|
||||
|
||||
// Middleware exige une session sauf pour /auth/* et les chemins publics. Sans
|
||||
// session : l'API répond 401 ; une navigation reçoit l'application, qui affiche
|
||||
// la page de connexion (ou, avec OIDC seul, est renvoyée vers le fournisseur).
|
||||
func (a *Auth) Middleware(next http.Handler, public func(string) bool) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
p := r.URL.Path
|
||||
if strings.HasPrefix(p, "/auth/") || public(p) {
|
||||
if u, ok := a.current(w, r); ok { // identité disponible sur les routes publiques (ex. /api/me)
|
||||
r = r.WithContext(WithUser(r.Context(), u))
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
u, ok := a.current(w, r)
|
||||
if ok {
|
||||
next.ServeHTTP(w, r.WithContext(WithUser(r.Context(), u)))
|
||||
return
|
||||
}
|
||||
if strings.HasPrefix(p, "/api/") || r.Method != http.MethodGet {
|
||||
if a.OnlyOIDC() {
|
||||
w.Header().Set(LoginHeader, "/auth/login")
|
||||
}
|
||||
writeErr(w, http.StatusUnauthorized, "connexion nécessaire")
|
||||
return
|
||||
}
|
||||
if a.OnlyOIDC() {
|
||||
loginRedirect(w)
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
// UserContext renvoie ctx portant l'utilisateur u (jetons d'API).
|
||||
func UserContext(ctx context.Context, u *User) context.Context { return WithUser(ctx, u) }
|
||||
@@ -0,0 +1,379 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto"
|
||||
"crypto/ecdsa"
|
||||
"crypto/elliptic"
|
||||
"crypto/hmac"
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"crypto/sha256"
|
||||
"crypto/tls"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"math/big"
|
||||
"net/http"
|
||||
"net/http/cookiejar"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// memNet est un « réseau » en mémoire : chaque hôte https est servi par un
|
||||
// http.Handler, sans ouvrir de port (les tests tournent aussi sous un bac à
|
||||
// sable qui interdit l'écoute locale).
|
||||
type memNet struct {
|
||||
hosts map[string]http.Handler
|
||||
n int
|
||||
}
|
||||
|
||||
var testNet = &memNet{hosts: map[string]http.Handler{}}
|
||||
|
||||
type memServer struct{ URL string }
|
||||
|
||||
// serve enregistre h sous un nouveau nom d'hôte et renvoie son URL.
|
||||
func (m *memNet) serve(prefix string, h http.Handler) *memServer {
|
||||
m.n++
|
||||
host := fmt.Sprintf("%s%d.test", prefix, m.n)
|
||||
m.hosts[host] = h
|
||||
return &memServer{URL: "https://" + host}
|
||||
}
|
||||
|
||||
func (m *memNet) RoundTrip(req *http.Request) (*http.Response, error) {
|
||||
h := m.hosts[req.URL.Host]
|
||||
if h == nil {
|
||||
return nil, fmt.Errorf("hôte inconnu : %s", req.URL.Host)
|
||||
}
|
||||
r := req.Clone(req.Context())
|
||||
r.RequestURI = req.URL.RequestURI()
|
||||
if r.Host == "" {
|
||||
r.Host = req.URL.Host
|
||||
}
|
||||
r.RemoteAddr = "192.0.2.1:4242"
|
||||
if req.URL.Scheme == "https" {
|
||||
r.TLS = &tls.ConnectionState{}
|
||||
}
|
||||
if r.Body == nil {
|
||||
r.Body = http.NoBody
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, r)
|
||||
res := rec.Result()
|
||||
res.Request = req
|
||||
return res, nil
|
||||
}
|
||||
|
||||
func (m *memNet) client() *http.Client { return &http.Client{Transport: m} }
|
||||
|
||||
// fakeIdP est un fournisseur OIDC minimal : découverte, autorisation (connexion
|
||||
// immédiate), jetons, JWKS et déconnexion.
|
||||
type fakeIdP struct {
|
||||
t *testing.T
|
||||
srv *memServer
|
||||
rsaKey *rsa.PrivateKey
|
||||
ecKey *ecdsa.PrivateKey
|
||||
alg string // RS256, ES256 ou HS256
|
||||
secret string
|
||||
groups []string
|
||||
|
||||
codes map[string]url.Values // code -> paramètres de la demande d'autorisation
|
||||
}
|
||||
|
||||
func newIdP(t *testing.T, alg string) *fakeIdP {
|
||||
rk, _ := rsa.GenerateKey(rand.Reader, 2048)
|
||||
ek, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||
p := &fakeIdP{t: t, rsaKey: rk, ecKey: ek, alg: alg, secret: "secret-client-assez-long", codes: map[string]url.Values{}}
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/.well-known/openid-configuration", func(w http.ResponseWriter, r *http.Request) {
|
||||
_ = json.NewEncoder(w).Encode(map[string]string{
|
||||
"issuer": p.srv.URL,
|
||||
"authorization_endpoint": p.srv.URL + "/authorize",
|
||||
"token_endpoint": p.srv.URL + "/token",
|
||||
"jwks_uri": p.srv.URL + "/jwks",
|
||||
"end_session_endpoint": p.srv.URL + "/logout",
|
||||
})
|
||||
})
|
||||
mux.HandleFunc("/jwks", func(w http.ResponseWriter, r *http.Request) {
|
||||
e := big.NewInt(int64(rk.E)).Bytes()
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"keys": []map[string]string{
|
||||
{"kty": "RSA", "kid": "r1", "use": "sig", "n": b64.EncodeToString(rk.N.Bytes()), "e": b64.EncodeToString(e)},
|
||||
{"kty": "EC", "kid": "e1", "crv": "P-256", "x": b64.EncodeToString(ek.X.FillBytes(make([]byte, 32))), "y": b64.EncodeToString(ek.Y.FillBytes(make([]byte, 32)))},
|
||||
}})
|
||||
})
|
||||
mux.HandleFunc("/authorize", func(w http.ResponseWriter, r *http.Request) {
|
||||
q := r.URL.Query()
|
||||
code := randomString(8)
|
||||
p.codes[code] = q
|
||||
http.Redirect(w, r, q.Get("redirect_uri")+"?code="+code+"&state="+url.QueryEscape(q.Get("state")), http.StatusFound)
|
||||
})
|
||||
mux.HandleFunc("/token", func(w http.ResponseWriter, r *http.Request) {
|
||||
_ = r.ParseForm()
|
||||
q, ok := p.codes[r.Form.Get("code")]
|
||||
delete(p.codes, r.Form.Get("code"))
|
||||
id, sec, _ := r.BasicAuth()
|
||||
ch := sha256.Sum256([]byte(r.Form.Get("code_verifier")))
|
||||
switch {
|
||||
case !ok, id != "excalicloud", sec != p.secret,
|
||||
r.Form.Get("redirect_uri") != q.Get("redirect_uri"),
|
||||
q.Get("code_challenge_method") != "S256", b64.EncodeToString(ch[:]) != q.Get("code_challenge"):
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
_, _ = w.Write([]byte(`{"error":"invalid_grant"}`))
|
||||
return
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(map[string]string{"id_token": p.idToken(q.Get("nonce")), "token_type": "Bearer"})
|
||||
})
|
||||
p.srv = testNet.serve("idp", mux)
|
||||
return p
|
||||
}
|
||||
|
||||
func (p *fakeIdP) idToken(nonce string) string {
|
||||
claims := map[string]any{
|
||||
"iss": p.srv.URL, "sub": "u-42", "aud": "excalicloud", "nonce": nonce,
|
||||
"exp": time.Now().Add(5 * time.Minute).Unix(), "iat": time.Now().Unix(),
|
||||
"preferred_username": "cedric", "email": "cedric@example.org",
|
||||
}
|
||||
if p.groups != nil {
|
||||
claims["groups"] = p.groups
|
||||
}
|
||||
return p.sign(claims)
|
||||
}
|
||||
|
||||
func (p *fakeIdP) sign(claims map[string]any) string {
|
||||
hdr := map[string]string{"alg": p.alg, "typ": "JWT"}
|
||||
switch p.alg {
|
||||
case "RS256":
|
||||
hdr["kid"] = "r1"
|
||||
case "ES256":
|
||||
hdr["kid"] = "e1"
|
||||
}
|
||||
hb, _ := json.Marshal(hdr)
|
||||
cb, _ := json.Marshal(claims)
|
||||
signed := b64.EncodeToString(hb) + "." + b64.EncodeToString(cb)
|
||||
d := sha256.Sum256([]byte(signed))
|
||||
var sig []byte
|
||||
switch p.alg {
|
||||
case "RS256":
|
||||
sig, _ = rsa.SignPKCS1v15(rand.Reader, p.rsaKey, crypto.SHA256, d[:])
|
||||
case "ES256":
|
||||
r, s, _ := ecdsa.Sign(rand.Reader, p.ecKey, d[:])
|
||||
sig = append(r.FillBytes(make([]byte, 32)), s.FillBytes(make([]byte, 32))...)
|
||||
case "HS256":
|
||||
m := hmac.New(sha256.New, []byte(p.secret))
|
||||
m.Write([]byte(signed))
|
||||
sig = m.Sum(nil)
|
||||
}
|
||||
return signed + "." + b64.EncodeToString(sig)
|
||||
}
|
||||
|
||||
// app démarre excalicloud (routes /auth/*, une API et une page protégées, un
|
||||
// chemin public) avec l'authentification OIDC.
|
||||
func app(t *testing.T, idp *fakeIdP, groups []string) (*memServer, *http.Client) {
|
||||
t.Helper()
|
||||
mux := http.NewServeMux()
|
||||
var srv *memServer
|
||||
o, err := NewOIDC(context.Background(), Config{
|
||||
Issuer: idp.srv.URL, ClientID: "excalicloud", ClientSecret: idp.secret,
|
||||
AllowedGroups: groups, EndSession: true, Secret: []byte("0123456789abcdef0123456789abcdef"),
|
||||
Client: testNet.client(),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
o.Register(mux)
|
||||
mux.HandleFunc("GET /api/me", func(w http.ResponseWriter, r *http.Request) {
|
||||
_ = json.NewEncoder(w).Encode(UserFrom(r.Context()))
|
||||
})
|
||||
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte("app")) })
|
||||
srv = testNet.serve("app", o.Middleware(mux, func(p string) bool { return strings.HasPrefix(p, "/s/") }))
|
||||
jar, _ := cookiejar.New(nil)
|
||||
return srv, &http.Client{Jar: jar, Transport: testNet}
|
||||
}
|
||||
|
||||
func get(t *testing.T, c *http.Client, u string) (*http.Response, string) {
|
||||
t.Helper()
|
||||
res, err := c.Get(u)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer res.Body.Close()
|
||||
b, _ := io.ReadAll(res.Body)
|
||||
return res, string(b)
|
||||
}
|
||||
|
||||
func TestLoginFlow(t *testing.T) {
|
||||
for _, alg := range []string{"RS256", "ES256", "HS256"} {
|
||||
t.Run(alg, func(t *testing.T) {
|
||||
idp := newIdP(t, alg)
|
||||
srv, c := app(t, idp, nil)
|
||||
|
||||
// Sans session : 401 avec l'adresse de connexion pour l'API...
|
||||
res, _ := get(t, c, srv.URL+"/api/me")
|
||||
if res.StatusCode != 401 || res.Header.Get(LoginHeader) != "/auth/login" {
|
||||
t.Fatalf("API sans session : %d %q", res.StatusCode, res.Header.Get(LoginHeader))
|
||||
}
|
||||
// ... page de redirection (fragment conservé) pour la navigation.
|
||||
res, body := get(t, c, srv.URL+"/")
|
||||
if res.StatusCode != 401 || !strings.Contains(body, "location.hash") {
|
||||
t.Fatalf("navigation sans session : %d", res.StatusCode)
|
||||
}
|
||||
// Chemin public accessible.
|
||||
if res, _ := get(t, c, srv.URL+"/s/x.y"); res.StatusCode != 200 {
|
||||
t.Fatalf("chemin public : %d", res.StatusCode)
|
||||
}
|
||||
|
||||
// Connexion complète : login -> fournisseur -> callback -> next.
|
||||
res, body = get(t, c, srv.URL+"/auth/login?next="+url.QueryEscape("/dossier?x=1"))
|
||||
if res.StatusCode != 200 || body != "app" || res.Request.URL.RequestURI() != "/dossier?x=1" {
|
||||
t.Fatalf("après connexion : %d %q %s", res.StatusCode, body, res.Request.URL)
|
||||
}
|
||||
res, body = get(t, c, srv.URL+"/api/me")
|
||||
if res.StatusCode != 200 || !strings.Contains(body, `"name":"cedric"`) || !strings.Contains(body, `"sub":"u-42"`) {
|
||||
t.Fatalf("/api/me : %d %s", res.StatusCode, body)
|
||||
}
|
||||
|
||||
// Déconnexion : cookie effacé, renvoi vers end_session_endpoint.
|
||||
nc := &http.Client{Jar: c.Jar, Transport: testNet, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
|
||||
res, _ = get(t, nc, srv.URL+"/auth/logout")
|
||||
loc, _ := url.Parse(res.Header.Get("Location"))
|
||||
if res.StatusCode != 302 || loc.Path != "/logout" || loc.Query().Get("client_id") != "excalicloud" ||
|
||||
loc.Query().Get("post_logout_redirect_uri") != srv.URL+"/auth/logged-out" {
|
||||
t.Fatalf("logout : %d %s", res.StatusCode, loc)
|
||||
}
|
||||
if res, _ := get(t, c, srv.URL+"/api/me"); res.StatusCode != 401 {
|
||||
t.Fatalf("après déconnexion : %d", res.StatusCode)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAllowedGroups(t *testing.T) {
|
||||
idp := newIdP(t, "RS256")
|
||||
idp.groups = []string{"/excalicloud-users"} // chemin complet Keycloak
|
||||
srv, c := app(t, idp, []string{"excalicloud-users"})
|
||||
if res, body := get(t, c, srv.URL+"/auth/login"); res.StatusCode != 200 || body != "app" {
|
||||
t.Fatalf("membre du groupe : %d %q", res.StatusCode, body)
|
||||
}
|
||||
|
||||
idp2 := newIdP(t, "RS256")
|
||||
idp2.groups = []string{"autres"}
|
||||
srv2, c2 := app(t, idp2, []string{"excalicloud-users"})
|
||||
if res, _ := get(t, c2, srv2.URL+"/auth/login"); res.StatusCode != 403 {
|
||||
t.Fatalf("hors groupe : %d", res.StatusCode)
|
||||
}
|
||||
if res, _ := get(t, c2, srv2.URL+"/api/me"); res.StatusCode != 401 {
|
||||
t.Fatalf("hors groupe, pas de session attendue : %d", res.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCallbackRejectsForgedState(t *testing.T) {
|
||||
idp := newIdP(t, "RS256")
|
||||
srv, c := app(t, idp, nil)
|
||||
// Callback sans cookie d'état (CSRF de connexion) : refusé.
|
||||
if res, _ := get(t, c, srv.URL+"/auth/callback?code=x&state=y"); res.StatusCode != 400 {
|
||||
t.Fatalf("callback forgé : %d", res.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyIDToken(t *testing.T) {
|
||||
idp := newIdP(t, "RS256")
|
||||
o, err := NewOIDC(context.Background(), Config{Issuer: idp.srv.URL, ClientID: "excalicloud", Secret: []byte("0123456789abcdef"), Client: testNet.client()})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
d, err := o.provider(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
base := func() map[string]any {
|
||||
return map[string]any{"iss": idp.srv.URL, "sub": "s", "aud": []string{"excalicloud"}, "nonce": "n",
|
||||
"exp": time.Now().Add(time.Minute).Unix(), "iat": time.Now().Unix()}
|
||||
}
|
||||
if _, err := o.verifyIDToken(context.Background(), d, idp.sign(base()), "n"); err != nil {
|
||||
t.Fatalf("jeton valide refusé : %v", err)
|
||||
}
|
||||
bad := map[string]func(map[string]any){
|
||||
"émetteur": func(c map[string]any) { c["iss"] = "https://ailleurs" },
|
||||
"audience": func(c map[string]any) { c["aud"] = "autre" },
|
||||
"expiré": func(c map[string]any) { c["exp"] = time.Now().Add(-time.Hour).Unix() },
|
||||
"nonce": func(c map[string]any) { c["nonce"] = "x" },
|
||||
}
|
||||
for name, mutate := range bad {
|
||||
c := base()
|
||||
mutate(c)
|
||||
if _, err := o.verifyIDToken(context.Background(), d, idp.sign(c), "n"); err == nil {
|
||||
t.Errorf("%s : jeton accepté", name)
|
||||
}
|
||||
}
|
||||
// Signature altérée, alg none et HS256 sans secret client.
|
||||
tok := idp.sign(base())
|
||||
if _, err := o.verifyIDToken(context.Background(), d, tok[:len(tok)-4]+"AAAA", "n"); err == nil {
|
||||
t.Error("signature altérée acceptée")
|
||||
}
|
||||
parts := strings.Split(tok, ".")
|
||||
none := b64.EncodeToString([]byte(`{"alg":"none"}`)) + "." + parts[1] + "."
|
||||
if _, err := o.verifyIDToken(context.Background(), d, none, "n"); err == nil {
|
||||
t.Error("alg none accepté")
|
||||
}
|
||||
idp.alg = "HS256"
|
||||
if _, err := o.verifyIDToken(context.Background(), d, idp.sign(base()), "n"); err == nil {
|
||||
t.Error("HS256 accepté sans secret client")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSafeNext(t *testing.T) {
|
||||
for in, want := range map[string]string{
|
||||
"/a/b?c=1": "/a/b?c=1",
|
||||
"//evil.example": "/",
|
||||
"/\\evil.example": "/",
|
||||
"https://evil": "/",
|
||||
"/auth/logout": "/",
|
||||
"": "/",
|
||||
"/x\r\nSet-Cookie:a": "/",
|
||||
} {
|
||||
if got := safeNext(in); got != want {
|
||||
t.Errorf("safeNext(%q) = %q, attendu %q", in, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionCookieTampering(t *testing.T) {
|
||||
s := signer{[]byte("0123456789abcdef")}
|
||||
v, _ := s.encode(session{User: User{Sub: "a"}, Exp: time.Now().Add(time.Hour).Unix()})
|
||||
var out session
|
||||
if err := s.decode(v, &out); err != nil || out.Sub != "a" {
|
||||
t.Fatalf("décodage : %v", err)
|
||||
}
|
||||
p, sig, _ := strings.Cut(v, ".")
|
||||
forged := b64.EncodeToString([]byte(`{"sub":"admin","exp":9999999999}`)) + "." + sig
|
||||
if s.decode(forged, &out) == nil || s.decode(p+".x", &out) == nil {
|
||||
t.Fatal("cookie altéré accepté")
|
||||
}
|
||||
if (signer{[]byte("autre-cle-0123456")}).decode(v, &out) == nil {
|
||||
t.Fatal("cookie signé par une autre clé accepté")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadSecret(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
if _, err := LoadSecret("court", dir); err == nil {
|
||||
t.Fatal("secret trop court accepté")
|
||||
}
|
||||
k1, err := LoadSecret("", dir)
|
||||
if err != nil || len(k1) != 32 {
|
||||
t.Fatalf("génération : %v", err)
|
||||
}
|
||||
fi, _ := os.Stat(filepath.Join(dir, ".session-secret"))
|
||||
if fi.Mode().Perm() != 0o600 {
|
||||
t.Fatalf("droits %v", fi.Mode().Perm())
|
||||
}
|
||||
k2, _ := LoadSecret("", dir)
|
||||
if string(k1) != string(k2) {
|
||||
t.Fatal("clé non conservée entre deux démarrages")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"crypto"
|
||||
"crypto/ecdsa"
|
||||
"crypto/elliptic"
|
||||
"crypto/hmac"
|
||||
"crypto/rsa"
|
||||
_ "crypto/sha256" // enregistre SHA-256 pour crypto.Hash
|
||||
_ "crypto/sha512" // enregistre SHA-384 et SHA-512
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math/big"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// jwk est une clé publique d'un JWKS (RFC 7517), RSA ou EC.
|
||||
type jwk struct {
|
||||
Kty string `json:"kty"`
|
||||
Kid string `json:"kid"`
|
||||
Use string `json:"use"`
|
||||
Alg string `json:"alg"`
|
||||
N string `json:"n"`
|
||||
E string `json:"e"`
|
||||
Crv string `json:"crv"`
|
||||
X string `json:"x"`
|
||||
Y string `json:"y"`
|
||||
}
|
||||
|
||||
func (k jwk) publicKey() (crypto.PublicKey, error) {
|
||||
switch k.Kty {
|
||||
case "RSA":
|
||||
n, err1 := b64.DecodeString(k.N)
|
||||
e, err2 := b64.DecodeString(k.E)
|
||||
if err1 != nil || err2 != nil || len(n) == 0 || len(e) == 0 || len(e) > 4 {
|
||||
return nil, errors.New("clé RSA invalide")
|
||||
}
|
||||
return &rsa.PublicKey{N: new(big.Int).SetBytes(n), E: int(new(big.Int).SetBytes(e).Int64())}, nil
|
||||
case "EC":
|
||||
var c elliptic.Curve
|
||||
switch k.Crv {
|
||||
case "P-256":
|
||||
c = elliptic.P256()
|
||||
case "P-384":
|
||||
c = elliptic.P384()
|
||||
case "P-521":
|
||||
c = elliptic.P521()
|
||||
default:
|
||||
return nil, fmt.Errorf("courbe %q non prise en charge", k.Crv)
|
||||
}
|
||||
x, err1 := b64.DecodeString(k.X)
|
||||
y, err2 := b64.DecodeString(k.Y)
|
||||
if err1 != nil || err2 != nil {
|
||||
return nil, errors.New("clé EC invalide")
|
||||
}
|
||||
pub := &ecdsa.PublicKey{Curve: c, X: new(big.Int).SetBytes(x), Y: new(big.Int).SetBytes(y)}
|
||||
if !c.IsOnCurve(pub.X, pub.Y) {
|
||||
return nil, errors.New("clé EC invalide")
|
||||
}
|
||||
return pub, nil
|
||||
}
|
||||
return nil, fmt.Errorf("type de clé %q non pris en charge", k.Kty)
|
||||
}
|
||||
|
||||
var algHash = map[string]crypto.Hash{
|
||||
"RS256": crypto.SHA256, "RS384": crypto.SHA384, "RS512": crypto.SHA512,
|
||||
"PS256": crypto.SHA256, "PS384": crypto.SHA384, "PS512": crypto.SHA512,
|
||||
"ES256": crypto.SHA256, "ES384": crypto.SHA384, "ES512": crypto.SHA512,
|
||||
"HS256": crypto.SHA256, "HS384": crypto.SHA384, "HS512": crypto.SHA512,
|
||||
}
|
||||
|
||||
type jwtHeader struct {
|
||||
Alg string `json:"alg"`
|
||||
Kid string `json:"kid"`
|
||||
}
|
||||
|
||||
// parseJWT découpe un JWS compact et renvoie l'en-tête, les claims bruts, le
|
||||
// contenu signé et la signature.
|
||||
func parseJWT(token string) (h jwtHeader, claims []byte, signed string, sig []byte, err error) {
|
||||
parts := strings.Split(token, ".")
|
||||
if len(parts) != 3 {
|
||||
return h, nil, "", nil, errors.New("jeton mal formé")
|
||||
}
|
||||
hb, err := b64.DecodeString(parts[0])
|
||||
if err != nil || json.Unmarshal(hb, &h) != nil {
|
||||
return h, nil, "", nil, errors.New("en-tête de jeton invalide")
|
||||
}
|
||||
if claims, err = b64.DecodeString(parts[1]); err != nil {
|
||||
return h, nil, "", nil, errors.New("contenu de jeton invalide")
|
||||
}
|
||||
if sig, err = b64.DecodeString(parts[2]); err != nil {
|
||||
return h, nil, "", nil, errors.New("signature de jeton invalide")
|
||||
}
|
||||
return h, claims, parts[0] + "." + parts[1], sig, nil
|
||||
}
|
||||
|
||||
// verifySignature vérifie la signature avec une clé publique (RS, PS, ES) ou
|
||||
// le secret client (HS, clé symétrique utilisée par exemple par Authentik
|
||||
// quand aucun certificat de signature n'est choisi).
|
||||
func verifySignature(alg string, key crypto.PublicKey, secret []byte, signed string, sig []byte) error {
|
||||
hash, ok := algHash[alg]
|
||||
if !ok {
|
||||
return fmt.Errorf("algorithme %q refusé", alg)
|
||||
}
|
||||
if strings.HasPrefix(alg, "HS") {
|
||||
if len(secret) == 0 {
|
||||
return fmt.Errorf("jeton %s sans OIDC_CLIENT_SECRET", alg)
|
||||
}
|
||||
m := hmac.New(hash.New, secret)
|
||||
m.Write([]byte(signed))
|
||||
if !hmac.Equal(m.Sum(nil), sig) {
|
||||
return errors.New("signature invalide")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
d := hash.New()
|
||||
d.Write([]byte(signed))
|
||||
digest := d.Sum(nil)
|
||||
switch k := key.(type) {
|
||||
case *rsa.PublicKey:
|
||||
var err error
|
||||
switch alg[:2] {
|
||||
case "RS":
|
||||
err = rsa.VerifyPKCS1v15(k, hash, digest, sig)
|
||||
case "PS":
|
||||
err = rsa.VerifyPSS(k, hash, digest, sig, &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash})
|
||||
default:
|
||||
err = errors.New("algorithme incompatible avec une clé RSA")
|
||||
}
|
||||
if err != nil {
|
||||
return errors.New("signature invalide")
|
||||
}
|
||||
return nil
|
||||
case *ecdsa.PublicKey:
|
||||
size := (k.Curve.Params().BitSize + 7) / 8
|
||||
if alg[:2] != "ES" || len(sig) != 2*size {
|
||||
return errors.New("signature invalide")
|
||||
}
|
||||
r, s := new(big.Int).SetBytes(sig[:size]), new(big.Int).SetBytes(sig[size:])
|
||||
if !ecdsa.Verify(k, digest, r, s) {
|
||||
return errors.New("signature invalide")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return errors.New("clé de vérification inadaptée")
|
||||
}
|
||||
|
||||
// idClaims regroupe les claims utiles d'un ID Token.
|
||||
type idClaims struct {
|
||||
Iss string `json:"iss"`
|
||||
Sub string `json:"sub"`
|
||||
Aud json.RawMessage `json:"aud"`
|
||||
Azp string `json:"azp"`
|
||||
Exp json.Number `json:"exp"`
|
||||
Iat json.Number `json:"iat"`
|
||||
Nonce string `json:"nonce"`
|
||||
Name string `json:"name"`
|
||||
PreferredUsername string `json:"preferred_username"`
|
||||
Email string `json:"email"`
|
||||
}
|
||||
|
||||
func (c idClaims) audiences() []string {
|
||||
var one string
|
||||
if json.Unmarshal(c.Aud, &one) == nil {
|
||||
return []string{one}
|
||||
}
|
||||
var many []string
|
||||
_ = json.Unmarshal(c.Aud, &many)
|
||||
return many
|
||||
}
|
||||
|
||||
const clockSkew = 2 * time.Minute
|
||||
|
||||
// validate contrôle émetteur, audience, dates et nonce (OIDC Core 3.1.3.7).
|
||||
func (c idClaims) validate(issuer, clientID, nonce string, t time.Time) error {
|
||||
if c.Iss != issuer {
|
||||
return fmt.Errorf("émetteur %q inattendu", c.Iss)
|
||||
}
|
||||
if c.Sub == "" {
|
||||
return errors.New("claim sub absent")
|
||||
}
|
||||
aud := c.audiences()
|
||||
found := false
|
||||
for _, a := range aud {
|
||||
found = found || a == clientID
|
||||
}
|
||||
if !found {
|
||||
return errors.New("jeton destiné à un autre client")
|
||||
}
|
||||
if len(aud) > 1 && c.Azp != "" && c.Azp != clientID {
|
||||
return errors.New("azp inattendu")
|
||||
}
|
||||
exp, err := c.Exp.Int64()
|
||||
if err != nil {
|
||||
f, ferr := c.Exp.Float64()
|
||||
if ferr != nil {
|
||||
return errors.New("claim exp invalide")
|
||||
}
|
||||
exp = int64(f)
|
||||
}
|
||||
if t.After(time.Unix(exp, 0).Add(clockSkew)) {
|
||||
return errors.New("jeton expiré")
|
||||
}
|
||||
if iat, err := c.Iat.Float64(); err == nil && time.Unix(int64(iat), 0).After(t.Add(clockSkew)) {
|
||||
return errors.New("jeton émis dans le futur (horloge ?)")
|
||||
}
|
||||
if !hmac.Equal([]byte(c.Nonce), []byte(nonce)) {
|
||||
return errors.New("nonce invalide")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// stringList lit un claim chaîne ou tableau de chaînes (groupes, rôles).
|
||||
func stringList(v any) []string {
|
||||
switch x := v.(type) {
|
||||
case string:
|
||||
return []string{x}
|
||||
case []any:
|
||||
out := make([]string, 0, len(x))
|
||||
for _, e := range x {
|
||||
if s, ok := e.(string); ok {
|
||||
out = append(out, s)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// claimPath lit un claim éventuellement imbriqué (« realm_access.roles »).
|
||||
func claimPath(all map[string]any, p string) any {
|
||||
var cur any = all
|
||||
for _, part := range strings.Split(p, ".") {
|
||||
m, ok := cur.(map[string]any)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
cur = m[part]
|
||||
}
|
||||
return cur
|
||||
}
|
||||
@@ -0,0 +1,571 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto"
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"html"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
sessionCookie = "upandown_session"
|
||||
stateCookie = "upandown_oidc"
|
||||
stateTTL = 10 * time.Minute
|
||||
|
||||
// LoginHeader accompagne les réponses 401 de l'API : le frontend y lit
|
||||
// l'adresse de connexion.
|
||||
LoginHeader = "X-Auth-Login"
|
||||
)
|
||||
|
||||
// Config regroupe les réglages OIDC (variables OIDC_* et SESSION_*).
|
||||
type Config struct {
|
||||
Issuer string // OIDC_ISSUER
|
||||
ClientID string // OIDC_CLIENT_ID
|
||||
ClientSecret string // OIDC_CLIENT_SECRET (vide : client public, PKCE seul)
|
||||
RedirectURL string // OIDC_REDIRECT_URL (vide : https://<hôte>/auth/callback)
|
||||
Scopes []string // OIDC_SCOPES
|
||||
// AllowedGroups restreint l'accès aux membres d'au moins un de ces groupes
|
||||
// (claim GroupsClaim) ; vide : tout utilisateur authentifié.
|
||||
AllowedGroups []string
|
||||
GroupsClaim string // OIDC_GROUPS_CLAIM, « groups » par défaut
|
||||
EndSession bool // OIDC_LOGOUT : déconnexion aussi chez le fournisseur
|
||||
SessionTTL time.Duration
|
||||
Secret []byte // clé HMAC des cookies
|
||||
Client *http.Client
|
||||
// Sessions : gestionnaire de sessions partagé avec l'authentification locale
|
||||
// (nil : créé à partir de Secret et SessionTTL).
|
||||
Sessions *Sessions
|
||||
// Provision est appelé après une connexion réussie, avant l'ouverture de la
|
||||
// session : il crée ou met à jour le compte et peut refuser la connexion
|
||||
// (ErrPending, ErrDisabled). Il renvoie l'utilisateur de la session.
|
||||
Provision func(u User, groups []string) (User, error)
|
||||
}
|
||||
|
||||
// discovery est la partie utile de /.well-known/openid-configuration.
|
||||
type discovery struct {
|
||||
Issuer string `json:"issuer"`
|
||||
AuthorizationEndpoint string `json:"authorization_endpoint"`
|
||||
TokenEndpoint string `json:"token_endpoint"`
|
||||
JWKSURI string `json:"jwks_uri"`
|
||||
EndSessionEndpoint string `json:"end_session_endpoint"`
|
||||
}
|
||||
|
||||
// OIDC authentifie les utilisateurs auprès d'un fournisseur OpenID Connect
|
||||
// (Authentik, Keycloak, Entra ID, Google, Dex...).
|
||||
type OIDC struct {
|
||||
cfg Config
|
||||
signer signer
|
||||
sess *Sessions
|
||||
|
||||
mu sync.Mutex
|
||||
disc *discovery // nil : pas encore découvert
|
||||
keys map[string]crypto.PublicKey
|
||||
keysAt time.Time
|
||||
discErr time.Time // dernier échec de découverte (limite les tentatives)
|
||||
}
|
||||
|
||||
// NewOIDC prépare l'authentification ; la découverte du fournisseur est
|
||||
// tentée tout de suite puis, en cas d'échec, à la première connexion.
|
||||
func NewOIDC(ctx context.Context, cfg Config) (*OIDC, error) {
|
||||
if cfg.Issuer == "" || cfg.ClientID == "" {
|
||||
return nil, errors.New("OIDC_ISSUER et OIDC_CLIENT_ID sont requis en mode oidc")
|
||||
}
|
||||
if len(cfg.Secret) < 16 {
|
||||
return nil, errors.New("clé de session trop courte")
|
||||
}
|
||||
if cfg.RedirectURL != "" {
|
||||
u, err := url.Parse(cfg.RedirectURL)
|
||||
if err != nil || (u.Scheme != "https" && u.Scheme != "http") || u.Host == "" {
|
||||
return nil, errors.New("OIDC_REDIRECT_URL invalide (URL absolue attendue)")
|
||||
}
|
||||
}
|
||||
if len(cfg.Scopes) == 0 {
|
||||
cfg.Scopes = []string{"openid", "profile", "email"}
|
||||
}
|
||||
if !slices.Contains(cfg.Scopes, "openid") {
|
||||
cfg.Scopes = append([]string{"openid"}, cfg.Scopes...)
|
||||
}
|
||||
if cfg.GroupsClaim == "" {
|
||||
cfg.GroupsClaim = "groups"
|
||||
}
|
||||
if cfg.SessionTTL <= 0 {
|
||||
cfg.SessionTTL = 24 * time.Hour
|
||||
}
|
||||
if cfg.Client == nil {
|
||||
cfg.Client = &http.Client{Timeout: 15 * time.Second}
|
||||
}
|
||||
if cfg.Sessions == nil {
|
||||
cfg.Sessions = NewSessions(cfg.Secret, cfg.SessionTTL, strings.HasPrefix(cfg.RedirectURL, "https://"))
|
||||
}
|
||||
a := &OIDC{cfg: cfg, signer: signer{cfg.Secret}, sess: cfg.Sessions}
|
||||
if _, err := a.provider(ctx); err != nil {
|
||||
slog.Warn("fournisseur OIDC injoignable, nouvel essai à la première connexion", "issuer", cfg.Issuer, "err", err)
|
||||
}
|
||||
return a, nil
|
||||
}
|
||||
|
||||
func (a *OIDC) getJSON(ctx context.Context, u string, v any) error {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set("Accept", "application/json")
|
||||
res, err := a.cfg.Client.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer res.Body.Close()
|
||||
if res.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("%s : HTTP %d", u, res.StatusCode)
|
||||
}
|
||||
return json.NewDecoder(io.LimitReader(res.Body, 1<<20)).Decode(v)
|
||||
}
|
||||
|
||||
// provider renvoie la configuration découverte (mise en cache).
|
||||
func (a *OIDC) provider(ctx context.Context) (*discovery, error) {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if a.disc != nil {
|
||||
return a.disc, nil
|
||||
}
|
||||
if time.Since(a.discErr) < 5*time.Second {
|
||||
return nil, errors.New("fournisseur OIDC injoignable")
|
||||
}
|
||||
var d discovery
|
||||
u := strings.TrimRight(a.cfg.Issuer, "/") + "/.well-known/openid-configuration"
|
||||
if err := a.getJSON(ctx, u, &d); err != nil {
|
||||
a.discErr = time.Now()
|
||||
return nil, err
|
||||
}
|
||||
if strings.TrimRight(d.Issuer, "/") != strings.TrimRight(a.cfg.Issuer, "/") {
|
||||
a.discErr = time.Now()
|
||||
return nil, fmt.Errorf("l'émetteur annoncé (%s) ne correspond pas à OIDC_ISSUER", d.Issuer)
|
||||
}
|
||||
if d.AuthorizationEndpoint == "" || d.TokenEndpoint == "" || d.JWKSURI == "" {
|
||||
a.discErr = time.Now()
|
||||
return nil, errors.New("configuration OIDC incomplète (authorization, token ou jwks absent)")
|
||||
}
|
||||
a.disc = &d
|
||||
slog.Info("fournisseur OIDC découvert", "issuer", d.Issuer)
|
||||
return a.disc, nil
|
||||
}
|
||||
|
||||
// key renvoie la clé publique kid, en rechargeant le JWKS si elle est
|
||||
// inconnue (rotation de clés), au plus une fois par minute.
|
||||
func (a *OIDC) key(ctx context.Context, d *discovery, kid, alg string) (crypto.PublicKey, error) {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
find := func() crypto.PublicKey {
|
||||
if k, ok := a.keys[kid]; ok {
|
||||
return k
|
||||
}
|
||||
if kid == "" && len(a.keys) == 1 {
|
||||
for _, k := range a.keys {
|
||||
return k
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if k := find(); k != nil {
|
||||
return k, nil
|
||||
}
|
||||
if time.Since(a.keysAt) < time.Minute && a.keys != nil {
|
||||
return nil, fmt.Errorf("clé %q inconnue", kid)
|
||||
}
|
||||
var set struct {
|
||||
Keys []jwk `json:"keys"`
|
||||
}
|
||||
if err := a.getJSON(ctx, d.JWKSURI, &set); err != nil {
|
||||
return nil, fmt.Errorf("JWKS : %w", err)
|
||||
}
|
||||
a.keys = map[string]crypto.PublicKey{}
|
||||
a.keysAt = time.Now()
|
||||
for _, j := range set.Keys {
|
||||
if j.Use != "" && j.Use != "sig" {
|
||||
continue
|
||||
}
|
||||
if pk, err := j.publicKey(); err == nil {
|
||||
a.keys[j.Kid] = pk
|
||||
}
|
||||
}
|
||||
if k := find(); k != nil {
|
||||
return k, nil
|
||||
}
|
||||
return nil, fmt.Errorf("clé %q absente du JWKS (alg %s)", kid, alg)
|
||||
}
|
||||
|
||||
// --- Routes /auth/* -----------------------------------------------------------
|
||||
|
||||
// Register ajoute /auth/login, /auth/callback, /auth/logout et /auth/logged-out.
|
||||
func (a *OIDC) Register(mux *http.ServeMux) {
|
||||
a.RegisterLogin(mux)
|
||||
mux.HandleFunc("GET /auth/logout", a.logout)
|
||||
mux.HandleFunc("POST /auth/logout", a.logout)
|
||||
}
|
||||
|
||||
// RegisterLogin ajoute /auth/login, /auth/callback et /auth/logged-out (la
|
||||
// déconnexion est alors portée par l'appelant, voir Auth).
|
||||
func (a *OIDC) RegisterLogin(mux *http.ServeMux) {
|
||||
mux.HandleFunc("GET /auth/login", a.login)
|
||||
mux.HandleFunc("GET /auth/callback", a.callback)
|
||||
mux.HandleFunc("GET /auth/logged-out", func(w http.ResponseWriter, r *http.Request) {
|
||||
page(w, http.StatusOK, "Déconnecté", "Vous êtes déconnecté.", "/", "Se reconnecter")
|
||||
})
|
||||
}
|
||||
|
||||
func secure(r *http.Request) bool {
|
||||
return r.TLS != nil || strings.EqualFold(r.Header.Get("X-Forwarded-Proto"), "https")
|
||||
}
|
||||
|
||||
// baseURL est l'origine publique du service : celle de OIDC_REDIRECT_URL si
|
||||
// elle est fixée, sinon celle de la requête (en-têtes X-Forwarded-* compris).
|
||||
func (a *OIDC) baseURL(r *http.Request) string {
|
||||
if a.cfg.RedirectURL != "" {
|
||||
u, _ := url.Parse(a.cfg.RedirectURL)
|
||||
return u.Scheme + "://" + u.Host
|
||||
}
|
||||
scheme := "http"
|
||||
if secure(r) {
|
||||
scheme = "https"
|
||||
}
|
||||
host := r.Host
|
||||
if h := r.Header.Get("X-Forwarded-Host"); h != "" {
|
||||
host, _, _ = strings.Cut(h, ",")
|
||||
host = strings.TrimSpace(host)
|
||||
}
|
||||
return scheme + "://" + host
|
||||
}
|
||||
|
||||
func (a *OIDC) redirectURL(r *http.Request) string {
|
||||
if a.cfg.RedirectURL != "" {
|
||||
return a.cfg.RedirectURL
|
||||
}
|
||||
return a.baseURL(r) + "/auth/callback"
|
||||
}
|
||||
|
||||
func (a *OIDC) setCookie(w http.ResponseWriter, r *http.Request, name, value, path string, ttl time.Duration) {
|
||||
c := &http.Cookie{
|
||||
Name: name,
|
||||
Value: value,
|
||||
Path: path,
|
||||
HttpOnly: true,
|
||||
Secure: secure(r) || strings.HasPrefix(a.cfg.RedirectURL, "https://"),
|
||||
SameSite: http.SameSiteLaxMode, // envoyé au retour du fournisseur (navigation GET)
|
||||
}
|
||||
if ttl < 0 {
|
||||
c.MaxAge = -1
|
||||
} else {
|
||||
c.Expires = now().Add(ttl)
|
||||
c.MaxAge = int(ttl / time.Second)
|
||||
}
|
||||
http.SetCookie(w, c)
|
||||
}
|
||||
|
||||
// safeNext n'accepte que les chemins locaux (pas de redirection ouverte).
|
||||
func safeNext(next string) string {
|
||||
if !strings.HasPrefix(next, "/") || strings.HasPrefix(next, "//") || strings.HasPrefix(next, "/\\") ||
|
||||
strings.HasPrefix(next, "/auth/") || strings.ContainsAny(next, "\r\n") {
|
||||
return "/"
|
||||
}
|
||||
return next
|
||||
}
|
||||
|
||||
func (a *OIDC) login(w http.ResponseWriter, r *http.Request) {
|
||||
d, err := a.provider(r.Context())
|
||||
if err != nil {
|
||||
slog.Error("OIDC : découverte", "err", err)
|
||||
page(w, http.StatusBadGateway, "Connexion impossible",
|
||||
"Le fournisseur d'identité est injoignable pour l'instant.", r.URL.RequestURI(), "Réessayer")
|
||||
return
|
||||
}
|
||||
st := loginState{
|
||||
State: randomString(24),
|
||||
Nonce: randomString(24),
|
||||
Verifier: randomString(48), // 64 caractères (RFC 7636 : 43 à 128)
|
||||
Next: safeNext(r.URL.Query().Get("next")),
|
||||
Exp: now().Add(stateTTL).Unix(),
|
||||
}
|
||||
v, err := a.signer.encode(st)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
a.setCookie(w, r, stateCookie, v, "/auth/", stateTTL)
|
||||
|
||||
challenge := sha256.Sum256([]byte(st.Verifier))
|
||||
q := url.Values{
|
||||
"response_type": {"code"},
|
||||
"client_id": {a.cfg.ClientID},
|
||||
"redirect_uri": {a.redirectURL(r)},
|
||||
"scope": {strings.Join(a.cfg.Scopes, " ")},
|
||||
"state": {st.State},
|
||||
"nonce": {st.Nonce},
|
||||
"code_challenge": {b64.EncodeToString(challenge[:])},
|
||||
"code_challenge_method": {"S256"},
|
||||
}
|
||||
sep := "?"
|
||||
if strings.Contains(d.AuthorizationEndpoint, "?") {
|
||||
sep = "&"
|
||||
}
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
http.Redirect(w, r, d.AuthorizationEndpoint+sep+q.Encode(), http.StatusFound)
|
||||
}
|
||||
|
||||
func (a *OIDC) callback(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
q := r.URL.Query()
|
||||
retry := "/auth/login"
|
||||
var st loginState
|
||||
c, err := r.Cookie(stateCookie)
|
||||
if err == nil {
|
||||
err = a.signer.decode(c.Value, &st)
|
||||
}
|
||||
if err == nil && st.Next != "/" {
|
||||
retry += "?next=" + url.QueryEscape(st.Next)
|
||||
}
|
||||
a.setCookie(w, r, stateCookie, "", "/auth/", -1) // usage unique
|
||||
if e := q.Get("error"); e != "" {
|
||||
slog.Warn("OIDC : refus du fournisseur", "error", e, "description", q.Get("error_description"))
|
||||
page(w, http.StatusForbidden, "Connexion refusée", "Le fournisseur d'identité a refusé la connexion ("+e+").", retry, "Réessayer")
|
||||
return
|
||||
}
|
||||
if err != nil || st.Exp < now().Unix() || st.State == "" || q.Get("state") != st.State {
|
||||
page(w, http.StatusBadRequest, "Connexion expirée",
|
||||
"La demande de connexion est expirée ou invalide (cookies bloqués ?).", retry, "Recommencer")
|
||||
return
|
||||
}
|
||||
user, err := a.exchange(r, q.Get("code"), st)
|
||||
if errors.Is(err, errForbidden) {
|
||||
slog.Warn("OIDC : accès refusé", "sub", user.Sub, "name", user.Name)
|
||||
page(w, http.StatusForbidden, "Accès refusé",
|
||||
"Votre compte ("+user.Name+") n'appartient à aucun groupe autorisé.", "/auth/logout", "Changer de compte")
|
||||
return
|
||||
}
|
||||
if errors.Is(err, ErrPending) {
|
||||
page(w, http.StatusForbidden, "Compte en attente", "Votre compte ("+user.Name+") doit être validé par un administrateur.", "/auth/logout", "Changer de compte")
|
||||
return
|
||||
}
|
||||
if errors.Is(err, ErrDisabled) {
|
||||
page(w, http.StatusForbidden, "Compte désactivé", "Votre compte ("+user.Name+") a été désactivé.", "/auth/logout", "Changer de compte")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
slog.Error("OIDC : échange du code", "err", err)
|
||||
page(w, http.StatusBadGateway, "Connexion impossible", "La vérification de l'identité a échoué.", retry, "Réessayer")
|
||||
return
|
||||
}
|
||||
if err := a.startSession(w, r, user); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
slog.Info("connexion OIDC", "sub", user.Sub, "name", user.Name)
|
||||
http.Redirect(w, r, st.Next, http.StatusFound)
|
||||
}
|
||||
|
||||
var errForbidden = errors.New("utilisateur hors des groupes autorisés")
|
||||
|
||||
// exchange échange le code contre les jetons, vérifie l'ID Token et en tire
|
||||
// l'utilisateur.
|
||||
func (a *OIDC) exchange(r *http.Request, code string, st loginState) (User, error) {
|
||||
ctx := r.Context()
|
||||
d, err := a.provider(ctx)
|
||||
if err != nil {
|
||||
return User{}, err
|
||||
}
|
||||
form := url.Values{
|
||||
"grant_type": {"authorization_code"},
|
||||
"code": {code},
|
||||
"redirect_uri": {a.redirectURL(r)},
|
||||
"code_verifier": {st.Verifier},
|
||||
"client_id": {a.cfg.ClientID},
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, d.TokenEndpoint, strings.NewReader(form.Encode()))
|
||||
if err != nil {
|
||||
return User{}, err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
req.Header.Set("Accept", "application/json")
|
||||
if a.cfg.ClientSecret != "" { // client_secret_basic (RFC 6749 2.3.1)
|
||||
req.SetBasicAuth(url.QueryEscape(a.cfg.ClientID), url.QueryEscape(a.cfg.ClientSecret))
|
||||
}
|
||||
res, err := a.cfg.Client.Do(req)
|
||||
if err != nil {
|
||||
return User{}, err
|
||||
}
|
||||
defer res.Body.Close()
|
||||
var tok struct {
|
||||
IDToken string `json:"id_token"`
|
||||
Error string `json:"error"`
|
||||
Desc string `json:"error_description"`
|
||||
}
|
||||
if err := json.NewDecoder(io.LimitReader(res.Body, 1<<20)).Decode(&tok); err != nil {
|
||||
return User{}, fmt.Errorf("réponse du token endpoint (HTTP %d) : %w", res.StatusCode, err)
|
||||
}
|
||||
if res.StatusCode != http.StatusOK || tok.IDToken == "" {
|
||||
return User{}, fmt.Errorf("token endpoint : HTTP %d %s %s", res.StatusCode, tok.Error, tok.Desc)
|
||||
}
|
||||
u, err := a.verifyIDToken(ctx, d, tok.IDToken, st.Nonce)
|
||||
if err != nil {
|
||||
return u, err
|
||||
}
|
||||
if a.cfg.Provision != nil {
|
||||
return a.cfg.Provision(u, u.Groups)
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
func (a *OIDC) verifyIDToken(ctx context.Context, d *discovery, raw, nonce string) (User, error) {
|
||||
h, body, signed, sig, err := parseJWT(raw)
|
||||
if err != nil {
|
||||
return User{}, err
|
||||
}
|
||||
var key crypto.PublicKey
|
||||
if !strings.HasPrefix(h.Alg, "HS") {
|
||||
if key, err = a.key(ctx, d, h.Kid, h.Alg); err != nil {
|
||||
return User{}, err
|
||||
}
|
||||
}
|
||||
if err := verifySignature(h.Alg, key, []byte(a.cfg.ClientSecret), signed, sig); err != nil {
|
||||
return User{}, err
|
||||
}
|
||||
var c idClaims
|
||||
if err := json.Unmarshal(body, &c); err != nil {
|
||||
return User{}, errors.New("claims illisibles")
|
||||
}
|
||||
if err := c.validate(d.Issuer, a.cfg.ClientID, nonce, now()); err != nil {
|
||||
return User{}, err
|
||||
}
|
||||
u := User{Sub: c.Sub, Email: c.Email, Name: c.PreferredUsername}
|
||||
for _, n := range []string{c.Name, c.Email, c.Sub} {
|
||||
if u.Name == "" {
|
||||
u.Name = n
|
||||
}
|
||||
}
|
||||
var all map[string]any
|
||||
_ = json.Unmarshal(body, &all)
|
||||
groups := stringList(claimPath(all, a.cfg.GroupsClaim))
|
||||
for i, g := range groups {
|
||||
groups[i] = strings.TrimPrefix(g, "/") // Keycloak : chemin complet du groupe
|
||||
}
|
||||
u.Groups = groups
|
||||
if len(a.cfg.AllowedGroups) > 0 {
|
||||
ok := slices.ContainsFunc(groups, func(g string) bool {
|
||||
// Keycloak préfixe les groupes par « / » quand le chemin complet est inclus.
|
||||
return slices.Contains(a.cfg.AllowedGroups, g) || slices.Contains(a.cfg.AllowedGroups, strings.TrimPrefix(g, "/"))
|
||||
})
|
||||
if !ok {
|
||||
return u, errForbidden
|
||||
}
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
func (a *OIDC) startSession(w http.ResponseWriter, r *http.Request, u User) error {
|
||||
return a.sess.Start(w, r, u)
|
||||
}
|
||||
|
||||
func (a *OIDC) logout(w http.ResponseWriter, r *http.Request) {
|
||||
a.sess.Clear(w, r)
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
back := a.baseURL(r) + "/auth/logged-out"
|
||||
if a.cfg.EndSession {
|
||||
if d, err := a.provider(r.Context()); err == nil && d.EndSessionEndpoint != "" {
|
||||
// RP-Initiated Logout 1.0 : client_id identifie le client sans id_token_hint.
|
||||
q := url.Values{"client_id": {a.cfg.ClientID}, "post_logout_redirect_uri": {back}}
|
||||
sep := "?"
|
||||
if strings.Contains(d.EndSessionEndpoint, "?") {
|
||||
sep = "&"
|
||||
}
|
||||
http.Redirect(w, r, d.EndSessionEndpoint+sep+q.Encode(), http.StatusFound)
|
||||
return
|
||||
}
|
||||
}
|
||||
http.Redirect(w, r, back, http.StatusFound)
|
||||
}
|
||||
|
||||
// --- Protection des routes -------------------------------------------------------
|
||||
|
||||
type ctxKey struct{}
|
||||
|
||||
// UserFrom renvoie l'utilisateur de la requête (nil hors session OIDC).
|
||||
func UserFrom(ctx context.Context) *User {
|
||||
u, _ := ctx.Value(ctxKey{}).(*User)
|
||||
return u
|
||||
}
|
||||
|
||||
// WithUser renvoie ctx portant l'utilisateur u (authentification par jeton d'API).
|
||||
func WithUser(ctx context.Context, u *User) context.Context {
|
||||
return context.WithValue(ctx, ctxKey{}, u)
|
||||
}
|
||||
|
||||
// Session renvoie l'utilisateur du cookie de session s'il est valide.
|
||||
func (a *OIDC) session(r *http.Request) (session, bool) { return a.sess.Get(r) }
|
||||
|
||||
// Middleware exige une session sauf pour /auth/* et les chemins publics.
|
||||
// Navigation sans session : page qui renvoie vers /auth/login en conservant
|
||||
// l'URL complète (fragment #/dossier/schéma compris). API : 401 + LoginHeader.
|
||||
// La session est prolongée à chaque requête passée la moitié de sa durée.
|
||||
func (a *OIDC) Middleware(next http.Handler, public func(string) bool) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
p := r.URL.Path
|
||||
if strings.HasPrefix(p, "/auth/") || public(p) {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
s, ok := a.session(r)
|
||||
if !ok {
|
||||
if strings.HasPrefix(p, "/api/") || r.Method != http.MethodGet {
|
||||
w.Header().Set(LoginHeader, "/auth/login")
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
_, _ = w.Write([]byte(`{"error":"session expirée : reconnexion nécessaire"}`))
|
||||
return
|
||||
}
|
||||
loginRedirect(w)
|
||||
return
|
||||
}
|
||||
if time.Until(time.Unix(s.Exp, 0)) < a.cfg.SessionTTL/2 {
|
||||
_ = a.startSession(w, r, s.User)
|
||||
}
|
||||
u := s.User
|
||||
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), ctxKey{}, &u)))
|
||||
})
|
||||
}
|
||||
|
||||
// loginRedirect renvoie vers /auth/login par script pour conserver le
|
||||
// fragment de l'URL, que le navigateur n'envoie pas au serveur.
|
||||
func loginRedirect(w http.ResponseWriter) {
|
||||
h := w.Header()
|
||||
h.Set("Content-Type", "text/html; charset=utf-8")
|
||||
h.Set("Cache-Control", "no-store")
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
_, _ = io.WriteString(w, `<!doctype html><meta charset="utf-8"><title>Connexion</title>
|
||||
<script>location.replace("/auth/login?next="+encodeURIComponent(location.pathname+location.search+location.hash))</script>
|
||||
<noscript><a href="/auth/login">Se connecter</a></noscript>`)
|
||||
}
|
||||
|
||||
// page affiche un message simple (erreur de connexion, déconnexion).
|
||||
func page(w http.ResponseWriter, status int, title, msg, link, label string) {
|
||||
h := w.Header()
|
||||
h.Set("Content-Type", "text/html; charset=utf-8")
|
||||
h.Set("Cache-Control", "no-store")
|
||||
w.WriteHeader(status)
|
||||
e := html.EscapeString
|
||||
_, _ = fmt.Fprintf(w, `<!doctype html><html lang="fr"><meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1"><title>%s</title>
|
||||
<style>body{font:16px system-ui,sans-serif;display:grid;place-items:center;min-height:90vh;margin:0;color:#1b1b1f;background:#fff}
|
||||
@media(prefers-color-scheme:dark){body{color:#e3e3e8;background:#121212}}main{max-width:28rem;padding:1rem;text-align:center}
|
||||
a{display:inline-block;margin-top:1rem;padding:.6rem 1.2rem;border-radius:8px;background:#6965db;color:#fff;text-decoration:none}</style>
|
||||
<main><h1>%s</h1><p>%s</p><a href="%s">%s</a></main></html>`, e(title), e(title), e(msg), e(link), e(label))
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
// Package auth fournit l'authentification OpenID Connect (flux Authorization
|
||||
// Code + PKCE) et les sessions signées associées, sans dépendance externe.
|
||||
package auth
|
||||
|
||||
import (
|
||||
"crypto/hmac"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// User est l'utilisateur authentifié. Sub est l'identifiant du fournisseur
|
||||
// OIDC (vide pour un compte local) ; ID est celui du compte (nom de son
|
||||
// espace personnel) ; Role n'est jamais lu du cookie : il vient du compte.
|
||||
type User struct {
|
||||
ID string `json:"id,omitempty"`
|
||||
Sub string `json:"sub,omitempty"`
|
||||
Name string `json:"name"`
|
||||
Email string `json:"email,omitempty"`
|
||||
Provider string `json:"provider,omitempty"` // "local" ou "oidc"
|
||||
Role string `json:"role,omitempty"` // "admin" ou "user" (rempli par le middleware)
|
||||
Groups []string `json:"-"` // groupes OIDC de la connexion en cours
|
||||
}
|
||||
|
||||
// session est le contenu du cookie de session (signé, non chiffré : il ne
|
||||
// contient que l'identité, pas de jeton).
|
||||
type session struct {
|
||||
User
|
||||
Exp int64 `json:"exp"`
|
||||
}
|
||||
|
||||
// loginState accompagne l'aller-retour vers le fournisseur (cookie de 10 min).
|
||||
type loginState struct {
|
||||
State string `json:"state"`
|
||||
Nonce string `json:"nonce"`
|
||||
Verifier string `json:"verifier"`
|
||||
Next string `json:"next"`
|
||||
Exp int64 `json:"exp"`
|
||||
}
|
||||
|
||||
var errBadCookie = errors.New("cookie invalide")
|
||||
|
||||
// Erreurs de connexion.
|
||||
var (
|
||||
ErrBadCredentials = errors.New("identifiant ou mot de passe incorrect")
|
||||
ErrPending = errors.New("compte en attente de validation par un administrateur")
|
||||
ErrDisabled = errors.New("compte désactivé")
|
||||
)
|
||||
|
||||
// signer signe et vérifie des valeurs JSON (HMAC-SHA256).
|
||||
type signer struct{ key []byte }
|
||||
|
||||
var b64 = base64.RawURLEncoding
|
||||
|
||||
func (s signer) mac(payload string) string {
|
||||
m := hmac.New(sha256.New, s.key)
|
||||
m.Write([]byte(payload))
|
||||
return b64.EncodeToString(m.Sum(nil))
|
||||
}
|
||||
|
||||
func (s signer) encode(v any) (string, error) {
|
||||
raw, err := json.Marshal(v)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
p := b64.EncodeToString(raw)
|
||||
return p + "." + s.mac(p), nil
|
||||
}
|
||||
|
||||
// decode vérifie la signature puis décode ; le contrôle d'expiration revient
|
||||
// à l'appelant (champ Exp).
|
||||
func (s signer) decode(value string, v any) error {
|
||||
p, sig, ok := strings.Cut(value, ".")
|
||||
if !ok || !hmac.Equal([]byte(sig), []byte(s.mac(p))) {
|
||||
return errBadCookie
|
||||
}
|
||||
raw, err := b64.DecodeString(p)
|
||||
if err != nil {
|
||||
return errBadCookie
|
||||
}
|
||||
if json.Unmarshal(raw, v) != nil {
|
||||
return errBadCookie
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func randomString(n int) string {
|
||||
b := make([]byte, n)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
panic(err) // crypto/rand ne échoue pas sur les systèmes supportés
|
||||
}
|
||||
return b64.EncodeToString(b)
|
||||
}
|
||||
|
||||
// LoadSecret renvoie la clé de signature des sessions : secret si fourni
|
||||
// (16 caractères minimum), sinon le contenu de dir/.session-secret, créé
|
||||
// aléatoirement au premier démarrage (0600).
|
||||
func LoadSecret(secret, dir string) ([]byte, error) {
|
||||
if secret != "" {
|
||||
if len(secret) < 16 {
|
||||
return nil, errors.New("SESSION_SECRET trop court (16 caractères minimum)")
|
||||
}
|
||||
return []byte(secret), nil
|
||||
}
|
||||
file := filepath.Join(dir, ".session-secret")
|
||||
if b, err := os.ReadFile(file); err == nil {
|
||||
if k, err := hex.DecodeString(strings.TrimSpace(string(b))); err == nil && len(k) >= 32 {
|
||||
return k, nil
|
||||
}
|
||||
return nil, errors.New(file + " invalide (supprimer le fichier pour en générer un nouveau)")
|
||||
} else if !errors.Is(err, os.ErrNotExist) {
|
||||
return nil, err
|
||||
}
|
||||
k := make([]byte, 32)
|
||||
if _, err := rand.Read(k); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := os.WriteFile(file, []byte(hex.EncodeToString(k)+"\n"), 0o600); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return k, nil
|
||||
}
|
||||
|
||||
func now() time.Time { return time.Now() }
|
||||
|
||||
// Sessions gère le cookie de session signé, commun aux comptes locaux et OIDC.
|
||||
type Sessions struct {
|
||||
signer signer
|
||||
TTL time.Duration
|
||||
secure bool // cookie Secure même si la requête n'arrive pas en HTTPS (URL publique en https)
|
||||
}
|
||||
|
||||
// NewSessions crée un gestionnaire de sessions : secret signe les cookies, ttl
|
||||
// est la durée d'inactivité maximale.
|
||||
func NewSessions(secret []byte, ttl time.Duration, forceSecure bool) *Sessions {
|
||||
if ttl <= 0 {
|
||||
ttl = 24 * time.Hour
|
||||
}
|
||||
return &Sessions{signer: signer{secret}, TTL: ttl, secure: forceSecure}
|
||||
}
|
||||
|
||||
func (s *Sessions) cookie(w http.ResponseWriter, r *http.Request, value string, ttl time.Duration) {
|
||||
c := &http.Cookie{
|
||||
Name: sessionCookie,
|
||||
Value: value,
|
||||
Path: "/",
|
||||
HttpOnly: true,
|
||||
Secure: secure(r) || s.secure,
|
||||
SameSite: http.SameSiteLaxMode, // envoyé au retour du fournisseur (navigation GET)
|
||||
}
|
||||
if ttl < 0 {
|
||||
c.MaxAge = -1
|
||||
} else {
|
||||
c.Expires = now().Add(ttl)
|
||||
c.MaxAge = int(ttl / time.Second)
|
||||
}
|
||||
http.SetCookie(w, c)
|
||||
}
|
||||
|
||||
// Start ouvre (ou prolonge) la session de u.
|
||||
func (s *Sessions) Start(w http.ResponseWriter, r *http.Request, u User) error {
|
||||
v, err := s.signer.encode(session{User: u, Exp: now().Add(s.TTL).Unix()})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
s.cookie(w, r, v, s.TTL)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Clear supprime le cookie de session.
|
||||
func (s *Sessions) Clear(w http.ResponseWriter, r *http.Request) { s.cookie(w, r, "", -1) }
|
||||
|
||||
// Get renvoie la session du cookie s'il est valide.
|
||||
func (s *Sessions) Get(r *http.Request) (session, bool) {
|
||||
var v session
|
||||
c, err := r.Cookie(sessionCookie)
|
||||
if err != nil || s.signer.decode(c.Value, &v) != nil || v.Exp < now().Unix() || (v.Sub == "" && v.ID == "") {
|
||||
return v, false
|
||||
}
|
||||
return v, true
|
||||
}
|
||||
Reference in new issue
Block a user