Files

474 lines
18 KiB
Go

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