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.
This commit is contained in:
@@ -87,6 +87,9 @@ func Mount(r chi.Router, pool *pgxpool.Pool, logger *slog.Logger, events *playev
|
||||
authed.Put("/me/timezone", h.handlePutTimezone)
|
||||
authed.Get("/me/api-token", h.handleGetMyAPIToken)
|
||||
authed.Post("/me/api-token", h.handleRegenerateMyAPIToken)
|
||||
authed.Get("/me/sessions", h.handleListMySessions)
|
||||
authed.Delete("/me/sessions/{id}", h.handleRevokeMySession)
|
||||
authed.Post("/me/sessions/logout-others", h.handleRevokeMyOtherSessions)
|
||||
|
||||
authed.Get("/artists", h.handleListArtists)
|
||||
authed.Get("/artists/{id}", h.handleGetArtist)
|
||||
|
||||
@@ -96,6 +96,11 @@ func (h *handlers) handleLogin(w http.ResponseWriter, r *http.Request) {
|
||||
UserID: user.ID,
|
||||
TokenHash: auth.HashSessionToken(token),
|
||||
UserAgent: r.UserAgent(),
|
||||
// Origin address, frozen at issue time. Compared against last_ip in
|
||||
// the active-sessions surface: a session that was born somewhere the
|
||||
// user recognises but is being used from somewhere they don't is the
|
||||
// case this whole surface exists to surface.
|
||||
Ip: auth.ClientIP(r),
|
||||
}); err != nil {
|
||||
h.logger.Error("api: insert session failed", "err", err)
|
||||
writeErr(w, apierror.InternalMsg("insert failed", err))
|
||||
|
||||
@@ -175,6 +175,7 @@ func (h *handlers) handleRegister(w http.ResponseWriter, r *http.Request) {
|
||||
UserID: user.ID,
|
||||
TokenHash: auth.HashSessionToken(sessionToken),
|
||||
UserAgent: r.UserAgent(),
|
||||
Ip: auth.ClientIP(r),
|
||||
}); err != nil {
|
||||
h.logger.Error("register: insert session failed", "err", err)
|
||||
writeErr(w, apierror.Internal(err))
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/audit"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/auth"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
|
||||
)
|
||||
|
||||
// errNoCurrentSession means the request authenticated but the middleware
|
||||
// didn't record which session did it — which should be impossible on a route
|
||||
// behind RequireUser. It matters because "log out everywhere else" is defined
|
||||
// by exclusion: without knowing which session is ours, the safe-looking
|
||||
// action would sign the caller out too.
|
||||
var errNoCurrentSession = errors.New("no session id in request context")
|
||||
|
||||
// sessionResp is one row of the active-sessions list.
|
||||
//
|
||||
// token_hash is absent, and that is the point of storing only a hash: it
|
||||
// never leaves the database, so this surface can list sessions without
|
||||
// handing out anything that could be replayed.
|
||||
type sessionResp struct {
|
||||
ID string `json:"id"`
|
||||
UserAgent string `json:"user_agent"`
|
||||
// CreatedIP is frozen at issue time; LastIP moves with the session. The
|
||||
// pair is what makes a stolen token legible — same device string, but an
|
||||
// address the user doesn't recognise.
|
||||
CreatedIP string `json:"created_ip"`
|
||||
LastIP string `json:"last_ip"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
LastSeenAt time.Time `json:"last_seen_at"`
|
||||
// Current marks the session making this request so the UI can label it
|
||||
// and not offer a "log out" that signs the user out of the page they're
|
||||
// standing on.
|
||||
Current bool `json:"current"`
|
||||
}
|
||||
|
||||
type revokedResp struct {
|
||||
Revoked int `json:"revoked"`
|
||||
}
|
||||
|
||||
// handleListMySessions implements GET /api/me/sessions.
|
||||
func (h *handlers) handleListMySessions(w http.ResponseWriter, r *http.Request) {
|
||||
user, ok := requireUser(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
// Absent id is tolerated here (unlike logout-others): the list still
|
||||
// renders, it just won't flag a current row.
|
||||
currentID, _ := auth.SessionIDFromContext(r.Context())
|
||||
|
||||
rows, err := dbq.New(h.pool).ListSessionsForUser(r.Context(), user.ID)
|
||||
if err != nil {
|
||||
h.logger.Error("list sessions: query failed", "err", err)
|
||||
writeErr(w, apierror.Internal(err))
|
||||
return
|
||||
}
|
||||
out := make([]sessionResp, 0, len(rows))
|
||||
for _, s := range rows {
|
||||
out = append(out, sessionResp{
|
||||
ID: uuidToString(s.ID),
|
||||
UserAgent: s.UserAgent,
|
||||
CreatedIP: s.CreatedIp,
|
||||
LastIP: s.LastIp,
|
||||
CreatedAt: s.CreatedAt.Time,
|
||||
LastSeenAt: s.LastSeenAt.Time,
|
||||
Current: s.ID == currentID,
|
||||
})
|
||||
}
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
}
|
||||
|
||||
// handleRevokeMySession implements DELETE /api/me/sessions/{id}.
|
||||
func (h *handlers) handleRevokeMySession(w http.ResponseWriter, r *http.Request) {
|
||||
user, ok := requireUser(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
id, ok := parseUUID(chi.URLParam(r, "id"))
|
||||
if !ok {
|
||||
// Malformed and belongs-to-someone-else collapse to one answer on
|
||||
// purpose: a distinguishable response would let a caller probe
|
||||
// whether another user's session id exists.
|
||||
writeErr(w, apierror.NotFound("session"))
|
||||
return
|
||||
}
|
||||
n, err := dbq.New(h.pool).DeleteSessionForUser(r.Context(), dbq.DeleteSessionForUserParams{
|
||||
ID: id,
|
||||
UserID: user.ID,
|
||||
})
|
||||
if err != nil {
|
||||
h.logger.Error("revoke session: delete failed", "err", err)
|
||||
writeErr(w, apierror.Internal(err))
|
||||
return
|
||||
}
|
||||
if n == 0 {
|
||||
writeErr(w, apierror.NotFound("session"))
|
||||
return
|
||||
}
|
||||
audit.WriteOrLog(r.Context(), h.pool, h.logger, user.ID, user.ID, audit.ActionSessionRevoke, nil)
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// handleRevokeMyOtherSessions implements POST /api/me/sessions/logout-others.
|
||||
func (h *handlers) handleRevokeMyOtherSessions(w http.ResponseWriter, r *http.Request) {
|
||||
user, ok := requireUser(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
currentID, ok := auth.SessionIDFromContext(r.Context())
|
||||
if !ok {
|
||||
// Refuse rather than guess: deleting "all but unknown" is deleting
|
||||
// all, which would log the caller out of the page they invoked this
|
||||
// from and look exactly like the attack they were defending against.
|
||||
h.logger.Error("revoke other sessions: no session id in context")
|
||||
writeErr(w, apierror.Internal(errNoCurrentSession))
|
||||
return
|
||||
}
|
||||
n, err := dbq.New(h.pool).DeleteOtherSessionsForUser(r.Context(), dbq.DeleteOtherSessionsForUserParams{
|
||||
UserID: user.ID,
|
||||
ID: currentID,
|
||||
})
|
||||
if err != nil {
|
||||
h.logger.Error("revoke other sessions: delete failed", "err", err)
|
||||
writeErr(w, apierror.Internal(err))
|
||||
return
|
||||
}
|
||||
audit.WriteOrLog(r.Context(), h.pool, h.logger, user.ID, user.ID, audit.ActionSessionRevokeOthers, nil)
|
||||
writeJSON(w, http.StatusOK, revokedResp{Revoked: int(n)})
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user