Files
upandown/internal/auth/auth.go

257 lines
7.6 KiB
Go

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