Files
minstrel/internal/api/me_sessions_test.go
T
bvandeusen d86af7397d
test-go / test (push) Successful in 55s
test-go / integration (push) Successful in 4m53s
feat(auth): active sessions API with origin/current IP — #370
Server half of the active-sessions surface. Web UI follows.

The operator wants this specifically to notice a compromised account, which
sets the bar: the addresses have to be trustworthy, or the feature is worse
than absent because it looks like evidence.

Migration 0052 adds created_ip + last_ip. Two columns, not one, and the pair
is the signal: a session issued at home and now being used from elsewhere is
the shape of a stolen token, and neither column alone can show that. Typed
text, matching the user_agent column beside it — these are displayed, never
queried by subnet, and inet round-trips through pgx as a netip.Prefix that
renders "1.2.3.4/32".

The rest of the schema was already waiting. Migration 0004 anticipated this
exactly: "last_seen_at enables an 'active sessions' UI later (not wired in
this plan) without schema churn." last_seen_at is live data — the auth
middleware already touches it per request — so last_ip rides that same
UPDATE for free.

Getting the address right is the substance here. Nothing extracted a client
IP anywhere before, and both obvious approaches are wrong:

- RemoteAddr alone shows the reverse proxy on every session, which is the
  normal self-hosted deployment. Noise shaped like data.
- Trusting X-Forwarded-For lets any client choose what its victim sees. A
  security surface an attacker can write to is worse than none.

So auth.ClientIP trusts the header only when the request actually arrived
from a proxy range. Public RemoteAddr means a direct connection, so XFF is
attacker-controlled and ignored outright. Private RemoteAddr means we walk
XFF right-to-left — proxies append, so the right end is what our own
infrastructure wrote — and take the first non-proxy address. A forged XFF
only prepends to the left end, which that walk never reaches. Unit-tested,
including both spoofing shapes.

Fails closed on a public-addressed proxy (separate host, CDN): we report the
proxy rather than trusting a forgeable header. Documented at the function.

Endpoints, all scoped by user_id per rule #47:

  GET    /api/me/sessions                → list, flagging the current row
  DELETE /api/me/sessions/{id}           → 204, or 404 if not yours
  POST   /api/me/sessions/logout-others  → {"revoked": n}

Keyed on session id alone, any household member could revoke another's
session by guessing a uuid, so the delete carries user_id in its WHERE and
:execrows distinguishes "not yours" (404) from a false 204. There's a test
that asserts the row actually survives, not merely that we returned 404.

The middleware now also puts the session id in context. logout-others is
defined by exclusion, and without knowing which session is ours the
safe-looking action deletes everything including the caller's — so it
refuses rather than guesses when the id is absent, and that refusal is
tested for non-deletion too.

audit_log.action is plain text with no CHECK, so the two new actions need no
migration (rule #36 checked, not assumed).

Codegen is real sqlc 1.31.1 via the container in `make generate` — docker is
present on this workstation even though Go and sqlc aren't — rather than the
hand-written .sql.go shortcut used in milestone #268.
2026-08-05 09:17:40 -04:00

227 lines
7.4 KiB
Go

package api
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"github.com/go-chi/chi/v5"
"github.com/jackc/pgx/v5/pgtype"
"github.com/jackc/pgx/v5/pgxpool"
"git.fabledsword.com/bvandeusen/minstrel/internal/auth"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
)
// seedSession inserts a session for userID and returns its id.
func seedSession(t *testing.T, pool *pgxpool.Pool, userID pgtype.UUID, ip string) pgtype.UUID {
t.Helper()
token, err := auth.MintSessionToken()
if err != nil {
t.Fatalf("mint: %v", err)
}
sess, err := dbq.New(pool).InsertSession(context.Background(), dbq.InsertSessionParams{
UserID: userID,
TokenHash: auth.HashSessionToken(token),
UserAgent: "test-agent",
Ip: ip,
})
if err != nil {
t.Fatalf("insert session: %v", err)
}
return sess.ID
}
// withSession attaches the user and current-session id the handlers expect
// from RequireUser.
func withSession(r *http.Request, user dbq.User, sessionID pgtype.UUID) *http.Request {
ctx := context.WithValue(r.Context(), userCtxKeyForTest(), user)
ctx = context.WithValue(ctx, auth.SessionIDCtxKeyForTest(), sessionID)
return r.WithContext(ctx)
}
// withURLParam wires a chi route param, which handlers read via chi.URLParam.
func withURLParam(r *http.Request, key, value string) *http.Request {
rctx := chi.NewRouteContext()
rctx.URLParams.Add(key, value)
return r.WithContext(context.WithValue(r.Context(), chi.RouteCtxKey, rctx))
}
// The rule #47 assertion. A delete keyed only on session id would let any
// household member revoke any other member's session by id — this pins that
// the user scope is actually in the WHERE clause and not just intended.
func TestRevokeMySession_CannotRevokeAnotherUsersSession(t *testing.T) {
h, pool := testHandlers(t)
alice := seedUser(t, pool, "alice", "hunter2", false)
bob := seedUser(t, pool, "bob", "hunter2", false)
bobSession := seedSession(t, pool, bob.ID, "203.0.113.9")
aliceSession := seedSession(t, pool, alice.ID, "203.0.113.1")
target := uuidToString(bobSession)
req := httptest.NewRequest(http.MethodDelete, "/api/me/sessions/"+target, nil)
req = withURLParam(req, "id", target)
req = withSession(req, alice, aliceSession)
w := httptest.NewRecorder()
h.handleRevokeMySession(w, req)
if w.Code != http.StatusNotFound {
t.Errorf("status = %d, want 404 (not another user's to revoke)", w.Code)
}
// The 404 must mean "didn't happen", not merely "wasn't reported".
var stillThere bool
if err := pool.QueryRow(context.Background(),
`SELECT EXISTS (SELECT 1 FROM sessions WHERE id = $1)`, bobSession,
).Scan(&stillThere); err != nil {
t.Fatalf("exists check: %v", err)
}
if !stillThere {
t.Error("bob's session was deleted by alice's request")
}
}
func TestRevokeMySession_DeletesOwnSession(t *testing.T) {
h, pool := testHandlers(t)
alice := seedUser(t, pool, "alice", "hunter2", false)
current := seedSession(t, pool, alice.ID, "203.0.113.1")
other := seedSession(t, pool, alice.ID, "198.51.100.7")
target := uuidToString(other)
req := httptest.NewRequest(http.MethodDelete, "/api/me/sessions/"+target, nil)
req = withURLParam(req, "id", target)
req = withSession(req, alice, current)
w := httptest.NewRecorder()
h.handleRevokeMySession(w, req)
if w.Code != http.StatusNoContent {
t.Fatalf("status = %d, want 204", w.Code)
}
var gone bool
if err := pool.QueryRow(context.Background(),
`SELECT NOT EXISTS (SELECT 1 FROM sessions WHERE id = $1)`, other,
).Scan(&gone); err != nil {
t.Fatalf("exists check: %v", err)
}
if !gone {
t.Error("session survived its own owner's revoke")
}
}
// "Log out everywhere else" must spare the caller — otherwise the button
// signs you out of the page you pressed it on, which is indistinguishable
// from the compromise it's meant to remedy.
func TestRevokeMyOtherSessions_SparesCurrentAndOtherUsers(t *testing.T) {
h, pool := testHandlers(t)
alice := seedUser(t, pool, "alice", "hunter2", false)
bob := seedUser(t, pool, "bob", "hunter2", false)
current := seedSession(t, pool, alice.ID, "203.0.113.1")
seedSession(t, pool, alice.ID, "198.51.100.7")
seedSession(t, pool, alice.ID, "198.51.100.8")
bobSession := seedSession(t, pool, bob.ID, "203.0.113.9")
req := httptest.NewRequest(http.MethodPost, "/api/me/sessions/logout-others", nil)
req = withSession(req, alice, current)
w := httptest.NewRecorder()
h.handleRevokeMyOtherSessions(w, req)
if w.Code != http.StatusOK {
t.Fatalf("status = %d, want 200", w.Code)
}
var body revokedResp
if err := json.NewDecoder(w.Body).Decode(&body); err != nil {
t.Fatalf("decode: %v", err)
}
if body.Revoked != 2 {
t.Errorf("revoked = %d, want 2 (alice's other two, not bob's)", body.Revoked)
}
var aliceRemaining, bobRemaining int
if err := pool.QueryRow(context.Background(),
`SELECT count(*) FROM sessions WHERE user_id = $1`, alice.ID,
).Scan(&aliceRemaining); err != nil {
t.Fatalf("count alice: %v", err)
}
if aliceRemaining != 1 {
t.Errorf("alice sessions = %d, want 1 (the current one)", aliceRemaining)
}
if err := pool.QueryRow(context.Background(),
`SELECT count(*) FROM sessions WHERE id = $1`, bobSession,
).Scan(&bobRemaining); err != nil {
t.Fatalf("count bob: %v", err)
}
if bobRemaining != 1 {
t.Error("bob's session was caught in alice's logout-others")
}
}
// Without a current-session id the exclusion has nothing to exclude, so the
// handler must refuse rather than delete everything.
func TestRevokeMyOtherSessions_RefusesWithoutCurrentSession(t *testing.T) {
h, pool := testHandlers(t)
alice := seedUser(t, pool, "alice", "hunter2", false)
seedSession(t, pool, alice.ID, "203.0.113.1")
req := httptest.NewRequest(http.MethodPost, "/api/me/sessions/logout-others", nil)
req = req.WithContext(context.WithValue(req.Context(), userCtxKeyForTest(), alice))
w := httptest.NewRecorder()
h.handleRevokeMyOtherSessions(w, req)
if w.Code != http.StatusInternalServerError {
t.Errorf("status = %d, want 500", w.Code)
}
var remaining int
if err := pool.QueryRow(context.Background(),
`SELECT count(*) FROM sessions WHERE user_id = $1`, alice.ID,
).Scan(&remaining); err != nil {
t.Fatalf("count: %v", err)
}
if remaining != 1 {
t.Errorf("sessions = %d, want 1 — refusing must not delete", remaining)
}
}
func TestListMySessions_FlagsCurrentAndScopesToUser(t *testing.T) {
h, pool := testHandlers(t)
alice := seedUser(t, pool, "alice", "hunter2", false)
bob := seedUser(t, pool, "bob", "hunter2", false)
current := seedSession(t, pool, alice.ID, "203.0.113.1")
seedSession(t, pool, alice.ID, "198.51.100.7")
seedSession(t, pool, bob.ID, "203.0.113.9")
req := httptest.NewRequest(http.MethodGet, "/api/me/sessions", nil)
req = withSession(req, alice, current)
w := httptest.NewRecorder()
h.handleListMySessions(w, req)
if w.Code != http.StatusOK {
t.Fatalf("status = %d, want 200", w.Code)
}
var got []sessionResp
if err := json.NewDecoder(w.Body).Decode(&got); err != nil {
t.Fatalf("decode: %v", err)
}
if len(got) != 2 {
t.Fatalf("sessions = %d, want 2 (bob's must not appear)", len(got))
}
currentCount := 0
for _, s := range got {
if s.Current {
currentCount++
if s.ID != uuidToString(current) {
t.Errorf("current flagged on %s, want %s", s.ID, uuidToString(current))
}
}
if s.CreatedIP == "" {
t.Error("created_ip empty — the whole point of the surface")
}
}
if currentCount != 1 {
t.Errorf("current-flagged rows = %d, want exactly 1", currentCount)
}
}