Files
OwnCord/Server/api/totp_handler_test.go
T
J3vbandClaude 36be31db43 fix: 11 defects from bughunt sweep across server, db and client (#1382)
* fix(ws): 1 defect(s) (OC-0001)

* fix(db): 1 defect(s) (OC-0002)

sanitizeFTSQuery filtered only characters, so FTS5's bareword boolean
keywords (AND, OR, NOT) reached MATCH as operators; a query in an
invalid operator position raised "fts5: syntax error" instead of
returning results. Drop those bareword tokens after sanitizing.

* fix(dm): 1 defect(s) (OC-0004)

* fix(ws): 1 defect(s) (OC-0005)

* fix(voice): 1 defect(s) (OC-0006)

Count the shared voice_max_video budget in streams rather than rows: a
single user publishing both camera and screenshare consumed one slot while
producing two live streams, letting a channel over-admit up to 2N streams
against an N-stream cap.

* fix(client): 2 defect(s) (OC-0007, OC-0009)

OC-0007: mark the active channel loading before invalidating its message
window on a full-ready resync, so MessageList shows the spinner instead
of the empty-channel state for the duration of the refetch.

OC-0009: fan USER_UPDATE renames out to voiceStore.voiceUsers, which
keeps its own frozen username copy, so the voice roster no longer shows
a stale name for the rest of the call.

* fix(admin): 1 defect(s) (OC-0010)

* fix(identity): 1 defect(s) (OC-0011)

* fix(ws): 1 defect(s) (OC-0003)

The public half of an invisible user's presence (PresenceOthersEvent, and
BroadcastPresence's own mapped payload) went out via broadcastExcludeLow on
the low-priority queue - the ephemeral, unsequenced, drop-on-overflow
transport built for typing indicators - while every other source of the same
user's presence shares the normal-priority queue. That split one user's
presence across two per-client FIFOs with different durability and different
drain order (writePump drains normal strictly before low), so a frame could
land out of order against a later connect/disconnect presence frame, or be
silently dropped with no replay recovery.

Adds Hub.BroadcastToAllExcept, which routes through the same h.broadcast
channel and seqMu-serialized deliverBroadcast as BroadcastToAll, carrying an
excludeUserID that deliverBroadcast applies via pubsub.Publish(TopicGlobal,
msg, excludeUserID).

* fix(ws): 1 defect(s) (OC-0008)

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-08-16 17:06:11 +02:00

703 lines
26 KiB
Go

package api_test
import (
"bytes"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"net/url"
"testing"
"time"
"github.com/owncord/server/auth"
)
// ─── POST /api/v1/auth/verify-totp ──────────────────────────────────────────
func TestVerifyTOTP_Success(t *testing.T) {
database := newAuthTestDB(t)
limiter := auth.NewRateLimiter()
router := buildAuthRouter(database, limiter)
// Create user with TOTP enabled.
secret, _ := auth.GenerateTOTPSecret()
hash, _ := auth.HashPassword("Password1!")
uid, _ := database.CreateUser(context.Background(), "totpuser", hash, 4)
_ = database.UpdateUserTOTPSecret(context.Background(), uid, &secret)
// Login should return requires_2fa + partial_token.
rr := postJSON(t, router, "/api/v1/auth/login", map[string]string{
"username": "totpuser",
"password": "Password1!",
})
if rr.Code != http.StatusOK {
t.Fatalf("login status = %d, want 200; body = %s", rr.Code, rr.Body.String())
}
var loginResp map[string]any
_ = json.NewDecoder(rr.Body).Decode(&loginResp)
if loginResp["requires_2fa"] != true {
t.Fatal("expected requires_2fa=true in login response")
}
partialToken, ok := loginResp["partial_token"].(string)
if !ok || partialToken == "" {
t.Fatal("expected non-empty partial_token")
}
// Generate valid TOTP code and verify.
code, err := auth.GenerateTOTPCode(secret, time.Now().UTC())
if err != nil {
t.Fatalf("GenerateTOTPCode: %v", err)
}
rr = postJSONWithToken(t, router, "/api/v1/auth/verify-totp", partialToken,
map[string]string{"code": code})
if rr.Code != http.StatusOK {
t.Errorf("verify-totp status = %d, want 200; body = %s", rr.Code, rr.Body.String())
}
var verifyResp map[string]any
_ = json.NewDecoder(rr.Body).Decode(&verifyResp)
if verifyResp["token"] == nil {
t.Error("verify-totp response missing session token")
}
}
func TestVerifyTOTP_InvalidCode(t *testing.T) {
database := newAuthTestDB(t)
limiter := auth.NewRateLimiter()
router := buildAuthRouter(database, limiter)
secret, _ := auth.GenerateTOTPSecret()
hash, _ := auth.HashPassword("Password1!")
uid, _ := database.CreateUser(context.Background(), "totpuser2", hash, 4)
_ = database.UpdateUserTOTPSecret(context.Background(), uid, &secret)
// Login to get partial token.
rr := postJSON(t, router, "/api/v1/auth/login", map[string]string{
"username": "totpuser2",
"password": "Password1!",
})
var loginResp map[string]any
_ = json.NewDecoder(rr.Body).Decode(&loginResp)
partialToken := loginResp["partial_token"].(string)
// Submit wrong code.
rr = postJSONWithToken(t, router, "/api/v1/auth/verify-totp", partialToken,
map[string]string{"code": "000000"})
if rr.Code != http.StatusUnauthorized {
t.Errorf("verify-totp with bad code: status = %d, want 401", rr.Code)
}
}
func TestVerifyTOTP_MissingToken(t *testing.T) {
database := newAuthTestDB(t)
limiter := auth.NewRateLimiter()
router := buildAuthRouter(database, limiter)
rr := postJSON(t, router, "/api/v1/auth/verify-totp",
map[string]string{"code": "123456"})
if rr.Code != http.StatusUnauthorized {
t.Errorf("verify-totp without token: status = %d, want 401", rr.Code)
}
}
func TestVerifyTOTP_InvalidPartialToken(t *testing.T) {
database := newAuthTestDB(t)
limiter := auth.NewRateLimiter()
router := buildAuthRouter(database, limiter)
rr := postJSONWithToken(t, router, "/api/v1/auth/verify-totp", "bogus-token",
map[string]string{"code": "123456"})
if rr.Code != http.StatusUnauthorized {
t.Errorf("verify-totp with bogus token: status = %d, want 401", rr.Code)
}
}
func TestVerifyTOTP_MalformedBody(t *testing.T) {
database := newAuthTestDB(t)
limiter := auth.NewRateLimiter()
router := buildAuthRouter(database, limiter)
// Need a valid partial token to get past the token check.
secret, _ := auth.GenerateTOTPSecret()
hash, _ := auth.HashPassword("Password1!")
uid, _ := database.CreateUser(context.Background(), "totpuser3", hash, 4)
_ = database.UpdateUserTOTPSecret(context.Background(), uid, &secret)
rr := postJSON(t, router, "/api/v1/auth/login", map[string]string{
"username": "totpuser3",
"password": "Password1!",
})
var loginResp map[string]any
_ = json.NewDecoder(rr.Body).Decode(&loginResp)
partialToken := loginResp["partial_token"].(string)
// Send invalid JSON.
req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/verify-totp",
bytes.NewReader([]byte("{invalid")))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+partialToken)
req.RemoteAddr = "127.0.0.1:9999"
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
t.Errorf("verify-totp with malformed body: status = %d, want 400", rec.Code)
}
}
func TestVerifyTOTP_ReplayProtection(t *testing.T) {
database := newAuthTestDB(t)
limiter := auth.NewRateLimiter()
router := buildAuthRouter(database, limiter)
secret, _ := auth.GenerateTOTPSecret()
hash, _ := auth.HashPassword("Password1!")
uid, _ := database.CreateUser(context.Background(), "totpuser4", hash, 4)
_ = database.UpdateUserTOTPSecret(context.Background(), uid, &secret)
code, _ := auth.GenerateTOTPCode(secret, time.Now().UTC())
// First login + verify — should succeed.
rr := postJSON(t, router, "/api/v1/auth/login", map[string]string{
"username": "totpuser4",
"password": "Password1!",
})
var resp1 map[string]any
_ = json.NewDecoder(rr.Body).Decode(&resp1)
token1 := resp1["partial_token"].(string)
rr = postJSONWithToken(t, router, "/api/v1/auth/verify-totp", token1,
map[string]string{"code": code})
if rr.Code != http.StatusOK {
t.Fatalf("first verify: status = %d, want 200", rr.Code)
}
// Second login + verify with same code — should fail (consumed token).
rr = postJSON(t, router, "/api/v1/auth/login", map[string]string{
"username": "totpuser4",
"password": "Password1!",
})
var resp2 map[string]any
_ = json.NewDecoder(rr.Body).Decode(&resp2)
token2 := resp2["partial_token"].(string)
rr = postJSONWithToken(t, router, "/api/v1/auth/verify-totp", token2,
map[string]string{"code": code})
// Code was already used in UsedTOTPCodeStore, so it should be rejected.
if rr.Code != http.StatusUnauthorized {
t.Errorf("replay code: status = %d, want 401", rr.Code)
}
}
// ─── POST /api/v1/users/me/totp/enable ──────────────────────────────────────
func TestEnableTOTP_Success(t *testing.T) {
database := newAuthTestDB(t)
limiter := auth.NewRateLimiter()
router := buildAuthRouter(database, limiter)
token := loginAndGetToken(t, router, database, "enableuser", 4)
rr := postJSONWithToken(t, router, "/api/v1/users/me/totp/enable", token,
map[string]string{"password": "Password1!"})
if rr.Code != http.StatusOK {
t.Errorf("enable-totp status = %d, want 200; body = %s", rr.Code, rr.Body.String())
}
var resp map[string]any
_ = json.NewDecoder(rr.Body).Decode(&resp)
if resp["qr_uri"] == nil || resp["qr_uri"] == "" {
t.Error("enable-totp response missing qr_uri")
}
}
func TestEnableTOTP_WrongPassword(t *testing.T) {
database := newAuthTestDB(t)
limiter := auth.NewRateLimiter()
router := buildAuthRouter(database, limiter)
token := loginAndGetToken(t, router, database, "enableuser2", 4)
rr := postJSONWithToken(t, router, "/api/v1/users/me/totp/enable", token,
map[string]string{"password": "wrongpassword"})
if rr.Code != http.StatusBadRequest {
t.Errorf("enable-totp with wrong password: status = %d, want 400", rr.Code)
}
}
func TestEnableTOTP_Unauthenticated(t *testing.T) {
database := newAuthTestDB(t)
limiter := auth.NewRateLimiter()
router := buildAuthRouter(database, limiter)
rr := postJSONWithToken(t, router, "/api/v1/users/me/totp/enable", "badtoken",
map[string]string{"password": "Password1!"})
if rr.Code != http.StatusUnauthorized {
t.Errorf("enable-totp unauthenticated: status = %d, want 401", rr.Code)
}
}
// ─── POST /api/v1/users/me/totp/confirm ─────────────────────────────────────
func TestConfirmTOTP_Success(t *testing.T) {
database := newAuthTestDB(t)
limiter := auth.NewRateLimiter()
router := buildAuthRouter(database, limiter)
token := loginAndGetToken(t, router, database, "confirmuser", 4)
// Step 1: Enable to get pending secret.
rr := postJSONWithToken(t, router, "/api/v1/users/me/totp/enable", token,
map[string]string{"password": "Password1!"})
if rr.Code != http.StatusOK {
t.Fatalf("enable: status = %d; body = %s", rr.Code, rr.Body.String())
}
var enableResp map[string]any
_ = json.NewDecoder(rr.Body).Decode(&enableResp)
qrURI, _ := enableResp["qr_uri"].(string)
// Extract secret from QR URI (otpauth://totp/...?secret=XXX&...)
secret := extractSecretFromURI(t, qrURI)
// Step 2: Generate valid code and confirm.
code, _ := auth.GenerateTOTPCode(secret, time.Now().UTC())
rr = postJSONWithToken(t, router, "/api/v1/users/me/totp/confirm", token,
map[string]string{"password": "Password1!", "code": code})
if rr.Code != http.StatusNoContent {
t.Errorf("confirm-totp: status = %d, want 204; body = %s", rr.Code, rr.Body.String())
}
// Verify TOTP is now stored on user.
user, _ := database.GetUserByUsername(context.Background(), "confirmuser")
if user == nil {
t.Fatal("user not found after confirm")
}
if user.TOTPSecret == nil {
t.Error("expected TOTPSecret to be set after confirm")
}
}
func TestConfirmTOTP_InvalidCode_Handler(t *testing.T) {
database := newAuthTestDB(t)
limiter := auth.NewRateLimiter()
router := buildAuthRouter(database, limiter)
token := loginAndGetToken(t, router, database, "confirmuser2", 4)
// Enable first.
postJSONWithToken(t, router, "/api/v1/users/me/totp/enable", token,
map[string]string{"password": "Password1!"})
// Confirm with wrong code.
rr := postJSONWithToken(t, router, "/api/v1/users/me/totp/confirm", token,
map[string]string{"password": "Password1!", "code": "000000"})
if rr.Code != http.StatusUnauthorized {
t.Errorf("confirm-totp with bad code: status = %d, want 401", rr.Code)
}
}
func TestConfirmTOTP_NoPendingEnrollment(t *testing.T) {
database := newAuthTestDB(t)
limiter := auth.NewRateLimiter()
router := buildAuthRouter(database, limiter)
token := loginAndGetToken(t, router, database, "confirmuser3", 4)
// Try to confirm without enable first.
rr := postJSONWithToken(t, router, "/api/v1/users/me/totp/confirm", token,
map[string]string{"password": "Password1!", "code": "123456"})
if rr.Code != http.StatusBadRequest {
t.Errorf("confirm-totp without enable: status = %d, want 400", rr.Code)
}
}
func TestConfirmTOTP_WrongPassword_Handler(t *testing.T) {
database := newAuthTestDB(t)
limiter := auth.NewRateLimiter()
router := buildAuthRouter(database, limiter)
token := loginAndGetToken(t, router, database, "confirmuser4", 4)
postJSONWithToken(t, router, "/api/v1/users/me/totp/enable", token,
map[string]string{"password": "Password1!"})
rr := postJSONWithToken(t, router, "/api/v1/users/me/totp/confirm", token,
map[string]string{"password": "wrong", "code": "123456"})
if rr.Code != http.StatusBadRequest {
t.Errorf("confirm-totp wrong password: status = %d, want 400", rr.Code)
}
}
// ─── DELETE /api/v1/users/me/totp ────────────────────────────────────────────
func TestDisableTOTP_Success(t *testing.T) {
database := newAuthTestDB(t)
limiter := auth.NewRateLimiter()
router := buildAuthRouter(database, limiter)
token := loginAndGetToken(t, router, database, "disableuser", 4)
// Enable and confirm TOTP first.
rr := postJSONWithToken(t, router, "/api/v1/users/me/totp/enable", token,
map[string]string{"password": "Password1!"})
var enableResp map[string]any
_ = json.NewDecoder(rr.Body).Decode(&enableResp)
secret := extractSecretFromURI(t, enableResp["qr_uri"].(string))
code, _ := auth.GenerateTOTPCode(secret, time.Now().UTC())
postJSONWithToken(t, router, "/api/v1/users/me/totp/confirm", token,
map[string]string{"password": "Password1!", "code": code})
// Now disable.
rr = deleteWithToken(t, router, "/api/v1/users/me/totp", token,
map[string]string{"password": "Password1!"})
if rr.Code != http.StatusNoContent {
t.Errorf("disable-totp: status = %d, want 204; body = %s", rr.Code, rr.Body.String())
}
}
func TestDisableTOTP_WrongPassword_Handler(t *testing.T) {
database := newAuthTestDB(t)
limiter := auth.NewRateLimiter()
router := buildAuthRouter(database, limiter)
token := loginAndGetToken(t, router, database, "disableuser2", 4)
rr := deleteWithToken(t, router, "/api/v1/users/me/totp", token,
map[string]string{"password": "wrong"})
if rr.Code != http.StatusBadRequest {
t.Errorf("disable-totp wrong password: status = %d, want 400", rr.Code)
}
}
func TestDisableTOTP_Unauthenticated(t *testing.T) {
database := newAuthTestDB(t)
limiter := auth.NewRateLimiter()
router := buildAuthRouter(database, limiter)
rr := deleteWithToken(t, router, "/api/v1/users/me/totp", "badtoken",
map[string]string{"password": "Password1!"})
if rr.Code != http.StatusUnauthorized {
t.Errorf("disable-totp unauthenticated: status = %d, want 401", rr.Code)
}
}
func TestDisableTOTP_BlockedByServerPolicy(t *testing.T) {
database := newAuthTestDB(t)
limiter := auth.NewRateLimiter()
router := buildAuthRouter(database, limiter)
token := loginAndGetToken(t, router, database, "disableuser3", 4)
// Enable require_2fa server policy.
_, _ = database.ExecContext(context.Background(), `INSERT OR REPLACE INTO settings (key, value) VALUES ('require_2fa', '1')`)
rr := deleteWithToken(t, router, "/api/v1/users/me/totp", token,
map[string]string{"password": "Password1!"})
if rr.Code != http.StatusForbidden {
t.Errorf("disable-totp with require_2fa: status = %d, want 403; body = %s", rr.Code, rr.Body.String())
}
}
// ─── API-token principals (nil session) and post-password bans ───────────────
func TestVerifyTOTP_BannedAfterPasswordStep(t *testing.T) {
database := newAuthTestDB(t)
limiter := auth.NewRateLimiter()
router := buildAuthRouter(database, limiter)
secret, _ := auth.GenerateTOTPSecret()
hash, _ := auth.HashPassword("Password1!")
uid, _ := database.CreateUser(context.Background(), "banafterpw", hash, 4)
_ = database.UpdateUserTOTPSecret(context.Background(), uid, &secret)
rr := postJSON(t, router, "/api/v1/auth/login", map[string]string{
"username": "banafterpw",
"password": "Password1!",
})
var loginResp map[string]any
_ = json.NewDecoder(rr.Body).Decode(&loginResp)
partialToken, _ := loginResp["partial_token"].(string)
if partialToken == "" {
t.Fatal("expected partial_token from login")
}
// The ban lands inside the 10-minute partial-token window; the sibling
// login path refuses banned users right after the password compare.
if err := database.BanUser(context.Background(), uid, "test ban", nil); err != nil {
t.Fatalf("BanUser: %v", err)
}
code, _ := auth.GenerateTOTPCode(secret, time.Now().UTC())
rr = postJSONWithToken(t, router, "/api/v1/auth/verify-totp", partialToken,
map[string]string{"code": code})
if rr.Code != http.StatusForbidden {
t.Errorf("verify-totp for banned user: status = %d, want 403; body = %s", rr.Code, rr.Body.String())
}
var verifyResp map[string]any
_ = json.NewDecoder(rr.Body).Decode(&verifyResp)
if verifyResp["token"] != nil {
t.Error("verify-totp issued a session token to a banned user")
}
}
func TestConfirmTOTP_APITokenPrincipal_RevokesAllSessions(t *testing.T) {
database := newAuthTestDB(t)
limiter := auth.NewRateLimiter()
router := buildAuthRouter(database, limiter)
sessionToken := loginAndGetToken(t, router, database, "apitotp1", 4)
user, _ := database.GetUserByUsername(context.Background(), "apitotp1")
if user == nil {
t.Fatal("user not found")
}
apiTok, _ := auth.GenerateToken()
if _, err := database.CreateAPIToken(context.Background(), user.ID, auth.HashToken(apiTok), "ci", nil); err != nil {
t.Fatalf("CreateAPIToken: %v", err)
}
rr := postJSONWithToken(t, router, "/api/v1/users/me/totp/enable", apiTok,
map[string]string{"password": "Password1!"})
if rr.Code != http.StatusOK {
t.Fatalf("enable via API token: status = %d; body = %s", rr.Code, rr.Body.String())
}
var enableResp map[string]any
_ = json.NewDecoder(rr.Body).Decode(&enableResp)
secret := extractSecretFromURI(t, enableResp["qr_uri"].(string))
code, _ := auth.GenerateTOTPCode(secret, time.Now().UTC())
rr = postJSONWithToken(t, router, "/api/v1/users/me/totp/confirm", apiTok,
map[string]string{"password": "Password1!", "code": code})
if rr.Code != http.StatusNoContent {
t.Fatalf("confirm via API token: status = %d; body = %s", rr.Code, rr.Body.String())
}
// A 2FA change from a sessionless principal must revoke EVERY login
// session (keep = 0), mirroring the change-password path — not skip
// revocation entirely.
if s, _ := database.GetSessionByTokenHash(context.Background(), auth.HashToken(sessionToken)); s != nil {
t.Error("login session survived a 2FA enable performed via API token; want all sessions revoked")
}
}
func TestDisableTOTP_APITokenPrincipal_RevokesAllSessions(t *testing.T) {
database := newAuthTestDB(t)
limiter := auth.NewRateLimiter()
router := buildAuthRouter(database, limiter)
hash, _ := auth.HashPassword("Password1!")
uid, _ := database.CreateUser(context.Background(), "apitotp2", hash, 4)
apiTok, _ := auth.GenerateToken()
if _, err := database.CreateAPIToken(context.Background(), uid, auth.HashToken(apiTok), "ci", nil); err != nil {
t.Fatalf("CreateAPIToken: %v", err)
}
// Enable + confirm 2FA via the API token first.
rr := postJSONWithToken(t, router, "/api/v1/users/me/totp/enable", apiTok,
map[string]string{"password": "Password1!"})
if rr.Code != http.StatusOK {
t.Fatalf("enable: status = %d; body = %s", rr.Code, rr.Body.String())
}
var enableResp map[string]any
_ = json.NewDecoder(rr.Body).Decode(&enableResp)
secret := extractSecretFromURI(t, enableResp["qr_uri"].(string))
code, _ := auth.GenerateTOTPCode(secret, time.Now().UTC())
rr = postJSONWithToken(t, router, "/api/v1/users/me/totp/confirm", apiTok,
map[string]string{"password": "Password1!", "code": code})
if rr.Code != http.StatusNoContent {
t.Fatalf("confirm: status = %d; body = %s", rr.Code, rr.Body.String())
}
// A login session created after enrollment must be revoked by the disable.
sessionToken, _ := auth.GenerateToken()
if _, err := database.CreateSession(context.Background(), uid, auth.HashToken(sessionToken), "test", "127.0.0.1"); err != nil {
t.Fatalf("CreateSession: %v", err)
}
rr = deleteWithToken(t, router, "/api/v1/users/me/totp", apiTok,
map[string]string{"password": "Password1!"})
if rr.Code != http.StatusNoContent {
t.Fatalf("disable via API token: status = %d; body = %s", rr.Code, rr.Body.String())
}
if s, _ := database.GetSessionByTokenHash(context.Background(), auth.HashToken(sessionToken)); s != nil {
t.Error("login session survived a 2FA disable performed via API token; want all sessions revoked")
}
}
// ─── OC-0011: DeleteOtherSessions failures must not be silent successes ──────
// TestConfirmTOTP_RevokeFailureSurfacesWarning locks down that when
// DeleteOtherSessions fails after a 2FA enable commits, the handler must not
// report unqualified success: it should mirror the ChangePassword contract
// (service/user.go:262-274 / api/profile_handler.go:377) and report a 200
// with an explicit warning, not a silent 204.
func TestConfirmTOTP_RevokeFailureSurfacesWarning(t *testing.T) {
database := newAuthTestDB(t)
limiter := auth.NewRateLimiter()
router := buildAuthRouter(database, limiter)
token := loginAndGetToken(t, router, database, "confirmrevokefail", 4)
user, _ := database.GetUserByUsername(context.Background(), "confirmrevokefail")
if user == nil {
t.Fatal("user not found")
}
// A second, unrelated session so DeleteOtherSessions has a row to delete
// (a DELETE that matches zero rows never fires a BEFORE DELETE trigger).
otherToken, _ := auth.GenerateToken()
if _, err := database.CreateSession(context.Background(), user.ID, auth.HashToken(otherToken), "other-device", "127.0.0.1"); err != nil {
t.Fatalf("CreateSession: %v", err)
}
// Step 1: enable to get a pending secret (before the trigger exists).
rr := postJSONWithToken(t, router, "/api/v1/users/me/totp/enable", token,
map[string]string{"password": "Password1!"})
if rr.Code != http.StatusOK {
t.Fatalf("enable: status = %d; body = %s", rr.Code, rr.Body.String())
}
var enableResp map[string]any
_ = json.NewDecoder(rr.Body).Decode(&enableResp)
secret := extractSecretFromURI(t, enableResp["qr_uri"].(string))
code, _ := auth.GenerateTOTPCode(secret, time.Now().UTC())
// Make every DELETE against sessions fail from here on, simulating a
// genuine DB-level failure (disk error, "database is closed" during
// shutdown) rather than a cancel race — the confirm call below already
// uses context.WithoutCancel, so a dead request cannot trigger this.
if _, err := database.ExecContext(context.Background(), `
CREATE TRIGGER block_delete_sessions
BEFORE DELETE ON sessions
BEGIN
SELECT RAISE(FAIL, 'delete blocked');
END;
`); err != nil {
t.Fatalf("create trigger: %v", err)
}
// Step 2: confirm. The secret update must still commit even though the
// session-revocation tail fails.
rr = postJSONWithToken(t, router, "/api/v1/users/me/totp/confirm", token,
map[string]string{"password": "Password1!", "code": code})
updated, _ := database.GetUserByUsername(context.Background(), "confirmrevokefail")
if updated == nil || updated.TOTPSecret == nil {
t.Fatal("expected TOTPSecret to be committed even though revocation failed")
}
if rr.Code != http.StatusOK {
t.Fatalf("confirm-totp with revoke failure: status = %d, want 200; body = %s", rr.Code, rr.Body.String())
}
var resp map[string]any
if err := json.NewDecoder(rr.Body).Decode(&resp); err != nil {
t.Fatalf("decode confirm response: %v", err)
}
if resp["warning"] == nil {
t.Error("expected a warning field when session revocation failed after totp enable")
}
// The other session must still be present — revocation genuinely failed,
// it was not silently skipped or falsely reported as revoked.
if s, _ := database.GetSessionByTokenHash(context.Background(), auth.HashToken(otherToken)); s == nil {
t.Error("other session should still exist: DeleteOtherSessions was blocked by the trigger")
}
}
// TestDisableTOTP_RevokeFailureSurfacesWarning is the handleDisableTOTP
// sibling of TestConfirmTOTP_RevokeFailureSurfacesWarning.
func TestDisableTOTP_RevokeFailureSurfacesWarning(t *testing.T) {
database := newAuthTestDB(t)
limiter := auth.NewRateLimiter()
router := buildAuthRouter(database, limiter)
token := loginAndGetToken(t, router, database, "disablerevokefail", 4)
user, _ := database.GetUserByUsername(context.Background(), "disablerevokefail")
if user == nil {
t.Fatal("user not found")
}
// Enable and confirm TOTP first (before the trigger exists).
rr := postJSONWithToken(t, router, "/api/v1/users/me/totp/enable", token,
map[string]string{"password": "Password1!"})
var enableResp map[string]any
_ = json.NewDecoder(rr.Body).Decode(&enableResp)
secret := extractSecretFromURI(t, enableResp["qr_uri"].(string))
code, _ := auth.GenerateTOTPCode(secret, time.Now().UTC())
rr = postJSONWithToken(t, router, "/api/v1/users/me/totp/confirm", token,
map[string]string{"password": "Password1!", "code": code})
if rr.Code != http.StatusNoContent {
t.Fatalf("setup confirm: status = %d; body = %s", rr.Code, rr.Body.String())
}
// A second, unrelated session so DeleteOtherSessions has a row to delete.
otherToken, _ := auth.GenerateToken()
if _, err := database.CreateSession(context.Background(), user.ID, auth.HashToken(otherToken), "other-device", "127.0.0.1"); err != nil {
t.Fatalf("CreateSession: %v", err)
}
if _, err := database.ExecContext(context.Background(), `
CREATE TRIGGER block_delete_sessions
BEFORE DELETE ON sessions
BEGIN
SELECT RAISE(FAIL, 'delete blocked');
END;
`); err != nil {
t.Fatalf("create trigger: %v", err)
}
rr = deleteWithToken(t, router, "/api/v1/users/me/totp", token,
map[string]string{"password": "Password1!"})
updated, _ := database.GetUserByUsername(context.Background(), "disablerevokefail")
if updated == nil || updated.TOTPSecret != nil {
t.Fatal("expected TOTPSecret to be cleared even though revocation failed")
}
if rr.Code != http.StatusOK {
t.Fatalf("disable-totp with revoke failure: status = %d, want 200; body = %s", rr.Code, rr.Body.String())
}
var resp map[string]any
if err := json.NewDecoder(rr.Body).Decode(&resp); err != nil {
t.Fatalf("decode disable response: %v", err)
}
if resp["warning"] == nil {
t.Error("expected a warning field when session revocation failed after totp disable")
}
if s, _ := database.GetSessionByTokenHash(context.Background(), auth.HashToken(otherToken)); s == nil {
t.Error("other session should still exist: DeleteOtherSessions was blocked by the trigger")
}
}
// ─── Helpers ─────────────────────────────────────────────────────────────────
// deleteWithToken sends a DELETE request with a JSON body and auth token.
func deleteWithToken(t *testing.T, router http.Handler, path, token string, body any) *httptest.ResponseRecorder {
t.Helper()
raw, _ := json.Marshal(body)
req := httptest.NewRequest(http.MethodDelete, path, bytes.NewReader(raw))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+token)
req.RemoteAddr = "127.0.0.1:9999"
rr := httptest.NewRecorder()
router.ServeHTTP(rr, req)
return rr
}
// extractSecretFromURI parses a TOTP otpauth:// URI and returns the secret parameter.
func extractSecretFromURI(t *testing.T, uri string) string {
t.Helper()
u, err := url.Parse(uri)
if err != nil {
t.Fatalf("parse otpauth URI: %v", err)
}
s := u.Query().Get("secret")
if s == "" {
t.Fatalf("no secret param in URI: %s", uri)
}
return s
}