190 lines
5.5 KiB
Go
190 lines
5.5 KiB
Go
// 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
|
|
}
|