Files
minstrel/internal/api/me_sessions.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

137 lines
4.6 KiB
Go

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)})
}