Files
OwnCord/Server/service/user_test.go
T
J3vbandClaude Fable 5 6afa9e974c refactor(server): thread context.Context through the db layer and all callers
Fixes all 109 golangci-lint findings (106 contextcheck, 1 gocritic,
2 gosec) that accumulated after D2 wired dbgen (whose queries take ctx)
under ctx-less db.DB wrappers while CI lint was quota-dead. No nolint
comments added; every finding fixed by genuinely threading context.

- db: all 138 hand-written db.DB methods take ctx first; the dbCtx()
  Background shim is deleted; raw Query/QueryRow/Exec/Begin use their
  Context variants; the four redundant ctx-less passthroughs removed.
  db.Auditor/WriteAudit gain ctx.
- Seams: permissions.Checker (DB iface, HasChannelPerm,
  RequireChannelAccess) and the service.Store interface mirror the new
  signatures (ws.EventStore and plugin.PluginStore already did).
- Callers: api/admin handlers use r.Context(); ws per-message paths use
  the connection ctx via DispatchV2; hub loops and startup wiring use
  context.Background(); service methods thread ctx where they have one
  and Background where no ctx exists. Public service surface reached by
  ctx-holding chains (PermissionService.HasChannelPerm/GetRoleForUser/
  RequireChannelAccess, message/dm/block/invite/profile methods) is now
  ctx-first.
- Detached (context.WithoutCancel) where cancellation would break an
  invariant, found by a 3-lens adversarial review of the diff:
  * voice-leave background retries (a dead webhook/connection ctx killed
    retry 2 before it ran, leaving ghost capacity-holding voice rows)
  * rollbackVoiceJoin's compensating delete (its trigger IS the cancel)
  * post-2FA-change DeleteOtherSessions and logout DeleteSession (the
    security tail of a committed change must not die with the request)
  * all api/ws audit writes (a banned user could suppress their own
    login_blocked_banned row by aborting the request mid-bcrypt)
  * admin backup VACUUM INTO (an interrupt left a truncated .db that
    the backup list presented as restorable)
  * post-commit message/edit refetches (a committed message must still
    fan out when the sender disconnects)
  * hub settings-cache refresh (one dead connection could pin stale
    values for the 30s TTL)
- gocritic rangeValCopy fixed (index iteration); gosec G306 excluded in
  config with justification (generated source must stay world-readable)
  instead of flipping genprotocol output to 0o600.

Verified: gofmt/vet, all four build-tag variants, full suite, deadlock
pass, full -race pass, golangci-lint 0 issues uncapped.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-23 17:03:52 +02:00

84 lines
2.8 KiB
Go

package service
import (
"context"
"errors"
"slices"
"testing"
"github.com/owncord/server/db"
)
// pwStore wraps a real *db.DB with controllable DeleteOtherSessions behavior
// and audit capture, so the committed-password partial-success contract (W2-2)
// is testable. Embedding *db.DB satisfies the service Store interface; the two
// overridden methods intercept the calls the contract turns on while every
// other call (UpdateUserPassword, GetUserByID) hits the real database.
type pwStore struct {
*db.DB
failRevokes int // number of DeleteOtherSessions calls that fail before succeeding
revokeCalls int
audits []string
}
func (f *pwStore) DeleteOtherSessions(_ context.Context, _, _ int64) (int64, error) {
f.revokeCalls++
if f.revokeCalls <= f.failRevokes {
return 0, errors.New("session table locked")
}
return 2, nil
}
func (f *pwStore) LogAudit(_ context.Context, _ int64, action, _ string, _ int64, _ string) error {
f.audits = append(f.audits, action)
return nil
}
// TestChangePassword_RevokeFailureIsPartialSuccess locks the W2-2 contract:
// once the password is committed, revocation failure must never surface as an
// error (the old password is dead; a "failed" report walks the user into the
// confirm lockout), and the audit row must still be written.
func TestChangePassword_RevokeFailureIsPartialSuccess(t *testing.T) {
database := newTestDB(t)
seedUser(t, database, &db.User{ID: 7, Username: "pat", PasswordHash: "oldhash"})
fs := &pwStore{DB: database, failRevokes: 99}
svc := NewUserService(fs)
res, err := svc.ChangePassword(context.Background(), 7, "newhash", 1)
if err != nil {
t.Fatalf("committed password change must not return an error: %v", err)
}
if !res.RevokeFailed {
t.Fatal("RevokeFailed should be set when revocation keeps failing")
}
if u, _ := database.GetUserByID(context.Background(), 7); u.PasswordHash != "newhash" {
t.Fatal("password should be committed")
}
if !slices.Contains(fs.audits, "password_change") {
t.Fatal("audit row must be written even when revocation fails")
}
}
// TestChangePassword_RetryRecoversRevocation: a single transient revocation
// failure is absorbed by the bounded compensating retry.
func TestChangePassword_RetryRecoversRevocation(t *testing.T) {
database := newTestDB(t)
seedUser(t, database, &db.User{ID: 7, Username: "pat", PasswordHash: "oldhash"})
fs := &pwStore{DB: database, failRevokes: 1}
svc := NewUserService(fs)
res, err := svc.ChangePassword(context.Background(), 7, "newhash", 1)
if err != nil {
t.Fatalf("ChangePassword: %v", err)
}
if res.RevokeFailed {
t.Fatal("retry should have recovered the revocation")
}
if res.SessionsRevoked != 2 {
t.Fatalf("SessionsRevoked = %d, want 2", res.SessionsRevoked)
}
if fs.revokeCalls != 2 {
t.Fatalf("expected exactly one retry (2 calls), got %d", fs.revokeCalls)
}
}