package api_test import ( "net/http" "testing" "time" "github.com/pquerna/otp/totp" ) // enableTOTP turns on TOTP for b and returns the secret and recovery codes. func (b *browser) enableTOTP() (string, []string) { b.t.Helper() st, setup := b.do("POST", "/api/v1/me/totp/setup", nil) if st != http.StatusOK { b.t.Fatalf("totp setup = %d %v", st, setup) } secret := setup["secret"].(string) code, _ := totp.GenerateCode(secret, time.Now()) st, body := b.do("POST", "/api/v1/me/totp/enable", map[string]any{"code": code}) if st != http.StatusOK { b.t.Fatalf("totp enable = %d %v", st, body) } var codes []string for _, c := range body["recovery_codes"].([]any) { codes = append(codes, c.(string)) } return secret, codes } func TestRecoveryCodes(t *testing.T) { e := newEnv(t) email := uniq("r") + "@example.test" owner := e.browser(t) owner.signup(email, uniq("rec-")) _, codes := owner.enableTOTP() if len(codes) != 10 { t.Fatalf("enable returned %d recovery codes, want 10", len(codes)) } login := func(code string) (int, map[string]any) { b := e.browser(t) if st, body := b.do("POST", "/api/v1/auth/login", map[string]any{"email": email, "password": "correct horse battery"}); body["status"] != "totp_required" { t.Fatalf("login = %d %v, want totp_required", st, body) } return b.do("POST", "/api/v1/auth/login/totp", map[string]any{"code": code}) } if st, body := login(codes[0]); st != http.StatusOK { t.Fatalf("login with recovery code = %d %v, want 200", st, body) } if st, _ := login(codes[0]); st != http.StatusUnauthorized { t.Errorf("login with used recovery code = %d, want 401", st) } if st, _ := login(" " + upper(codes[1][:5]) + " " + codes[1][6:]); st != http.StatusOK { t.Errorf("login with reformatted recovery code = %d, want 200", st) } if _, me := owner.do("GET", "/api/v1/me", nil); me["recovery_codes_left"] != float64(8) { t.Errorf("recovery_codes_left = %v, want 8", me["recovery_codes_left"]) } st, body := owner.do("POST", "/api/v1/me/totp/recovery-codes", map[string]any{"password": "correct horse battery", "code": codes[2]}) if st != http.StatusOK || len(body["recovery_codes"].([]any)) != 10 { t.Fatalf("regenerate = %d %v, want 200 with 10 codes", st, body) } if st, _ := login(codes[3]); st != http.StatusUnauthorized { t.Errorf("login with code from replaced set = %d, want 401", st) } if st, _ := login(body["recovery_codes"].([]any)[0].(string)); st != http.StatusOK { t.Errorf("login with code from new set = %d, want 200", st) } st, _ = owner.do("POST", "/api/v1/me/totp/recovery-codes", map[string]any{"password": "wrong password!!", "code": codes[4]}) if st != http.StatusUnauthorized { t.Errorf("regenerate with wrong password = %d, want 401", st) } } func upper(s string) string { b := []byte(s) for i, c := range b { if c >= 'a' && c <= 'z' { b[i] = c - 32 } } return string(b) }