feat(auth): active sessions API with origin/current IP — #370
test-go / test (push) Successful in 55s
test-go / integration (push) Successful in 4m53s

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:
2026-08-05 09:17:40 -04:00
parent 2e1a8a62d8
commit d86af7397d
15 changed files with 771 additions and 14 deletions
+92
View File
@@ -0,0 +1,92 @@
package auth
import (
"net"
"net/http"
"strings"
)
// ClientIP returns the caller's address for the active-sessions surface (#370).
//
// Both obvious implementations are wrong, and they're wrong in ways that
// matter specifically because this feeds a compromise-detection UI:
//
// - r.RemoteAddr alone. Minstrel is normally behind a reverse proxy, so
// every session would show the proxy's address — noise shaped like data,
// hiding the exact thing the operator is looking for.
// - Trusting X-Forwarded-For. Any client can set that header, so an
// attacker could choose what appears in their victim's session list.
// A security surface an attacker can write to is worse than none.
//
// So the header is trusted only when the request actually arrived from a
// proxy. If RemoteAddr is public, the caller reached us directly and its XFF
// is attacker-controlled, so it's ignored outright. If RemoteAddr is
// private/loopback, XFF is walked from the RIGHT — entries are appended as a
// request passes through infrastructure, so the rightmost end is the one our
// own proxies wrote — and the first address that isn't itself a proxy range
// wins. A client forging XFF can only prepend to the untrusted left end,
// which that walk never reaches.
//
// Known limitation, failing closed on purpose: if the proxy sits on a PUBLIC
// address (a separate host, or a CDN in front), RemoteAddr isn't in a proxy
// range, so we report the proxy rather than the end user. That's a true fact
// about where the request came from, which beats trusting a forgeable header.
//
// Returns "" when nothing usable can be determined. Callers store that as-is
// and the UI renders "unknown" rather than inventing a value.
func ClientIP(r *http.Request) string {
remote := hostOf(r.RemoteAddr)
ip := net.ParseIP(remote)
if ip == nil || !isProxyRange(ip) {
return remote
}
if forwarded := forwardedClient(r.Header.Get("X-Forwarded-For")); forwarded != "" {
return forwarded
}
// Some proxies set only X-Real-IP. The trust condition is already
// satisfied — we know this request came from a proxy range.
if real := net.ParseIP(strings.TrimSpace(r.Header.Get("X-Real-IP"))); real != nil {
return real.String()
}
return remote
}
// hostOf strips the port from a RemoteAddr, tolerating values that have none.
func hostOf(remoteAddr string) string {
host, _, err := net.SplitHostPort(remoteAddr)
if err != nil {
return strings.TrimSpace(remoteAddr)
}
return host
}
// forwardedClient walks an X-Forwarded-For value right-to-left and returns
// the first address outside our proxy ranges — see ClientIP for why the
// direction matters. Returns "" if the header is absent, malformed, or
// contains nothing but proxy addresses.
func forwardedClient(header string) string {
parts := strings.Split(header, ",")
for i := len(parts) - 1; i >= 0; i-- {
ip := net.ParseIP(strings.TrimSpace(parts[i]))
if ip == nil || isProxyRange(ip) {
continue
}
return ip.String()
}
return ""
}
// isProxyRange reports whether ip is an address a reverse proxy would
// plausibly occupy in a self-hosted deployment: loopback, RFC1918 / ULA
// (both covered by IsPrivate), link-local, or unspecified.
//
// Deliberately not configurable. These ranges cover proxy-on-same-host and
// proxy-on-the-same-docker-network, which is essentially every self-hosted
// install, and it works with no setup at all (rule #26). An exotic topology
// can motivate a setting when one actually turns up.
func isProxyRange(ip net.IP) bool {
return ip.IsLoopback() ||
ip.IsPrivate() ||
ip.IsLinkLocalUnicast() ||
ip.IsUnspecified()
}
+121
View File
@@ -0,0 +1,121 @@
package auth
import (
"net/http"
"testing"
)
// The spoofing cases below are the reason this function exists rather than a
// one-line r.RemoteAddr read, so they're asserted explicitly rather than
// folded into the happy-path table.
func TestClientIP(t *testing.T) {
tests := []struct {
name string
remoteAddr string
forwarded string
realIP string
want string
}{
{
name: "direct connection, no proxy headers",
remoteAddr: "203.0.113.5:51234",
want: "203.0.113.5",
},
{
// The attack this guards against: a client connecting straight to
// us claims to be someone else. RemoteAddr is public, so it did
// NOT come through our proxy, so its XFF is worthless.
name: "direct connection ignores forged X-Forwarded-For",
remoteAddr: "203.0.113.5:51234",
forwarded: "198.51.100.99",
want: "203.0.113.5",
},
{
name: "direct connection ignores forged X-Real-IP",
remoteAddr: "203.0.113.5:51234",
realIP: "198.51.100.99",
want: "203.0.113.5",
},
{
name: "behind proxy, single forwarded client",
remoteAddr: "172.18.0.1:40000",
forwarded: "203.0.113.5",
want: "203.0.113.5",
},
{
// A client that prepends a lie to XFF only pollutes the LEFT end;
// the proxy appends the address it actually saw on the right. The
// right-to-left walk reaches the truth first.
name: "behind proxy, forged prefix is skipped for the appended truth",
remoteAddr: "10.0.0.2:40000",
forwarded: "198.51.100.99, 203.0.113.5",
want: "203.0.113.5",
},
{
name: "behind proxy chain, internal hops skipped",
remoteAddr: "10.0.0.2:40000",
forwarded: "203.0.113.5, 10.0.0.7, 172.18.0.3",
want: "203.0.113.5",
},
{
name: "behind proxy, X-Real-IP used when no forwarded header",
remoteAddr: "127.0.0.1:40000",
realIP: "203.0.113.5",
want: "203.0.113.5",
},
{
// LAN client through a LAN proxy: everything is private, so there
// is no public address to find. Reporting the peer is honest.
name: "behind proxy, all-private chain falls back to remote",
remoteAddr: "172.18.0.1:40000",
forwarded: "192.168.1.50, 172.18.0.3",
want: "172.18.0.1",
},
{
name: "behind proxy, malformed forwarded entries ignored",
remoteAddr: "172.18.0.1:40000",
forwarded: "not-an-ip, 203.0.113.5, also-garbage",
want: "203.0.113.5",
},
{
name: "remote addr without a port is tolerated",
remoteAddr: "203.0.113.5",
want: "203.0.113.5",
},
{
name: "ipv6 remote addr",
remoteAddr: "[2001:db8::1]:51234",
want: "2001:db8::1",
},
{
name: "ipv6 forwarded client behind proxy",
remoteAddr: "[fd00::1]:40000",
forwarded: "2001:db8::5",
want: "2001:db8::5",
},
{
name: "empty remote addr yields empty",
remoteAddr: "",
want: "",
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
r, err := http.NewRequest(http.MethodGet, "/api/me/sessions", nil)
if err != nil {
t.Fatalf("NewRequest: %v", err)
}
r.RemoteAddr = tc.remoteAddr
if tc.forwarded != "" {
r.Header.Set("X-Forwarded-For", tc.forwarded)
}
if tc.realIP != "" {
r.Header.Set("X-Real-IP", tc.realIP)
}
if got := ClientIP(r); got != tc.want {
t.Errorf("ClientIP() = %q, want %q", got, tc.want)
}
})
}
}
+16 -1
View File
@@ -3,12 +3,17 @@ package auth
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
)
type ctxKey int
const userCtxKey ctxKey = 1
const (
userCtxKey ctxKey = 1
sessionIDCtxKey ctxKey = 2
)
// UserFromContext returns the authenticated user placed in context by
// RequireUser. Returns false when RequireUser has not run (e.g. in tests that
@@ -17,3 +22,13 @@ func UserFromContext(ctx context.Context) (dbq.User, bool) {
u, ok := ctx.Value(userCtxKey).(dbq.User)
return u, ok
}
// SessionIDFromContext returns the id of the session that authenticated this
// request. The active-sessions surface needs it for the two things it can't
// do from the user alone: mark which row is "this device", and exclude that
// row from "log out everywhere else" so the action doesn't sign the caller
// out of the page they invoked it from.
func SessionIDFromContext(ctx context.Context) (pgtype.UUID, bool) {
id, ok := ctx.Value(sessionIDCtxKey).(pgtype.UUID)
return id, ok
}
+15 -1
View File
@@ -98,10 +98,17 @@ func RequireUser(pool *pgxpool.Pool) func(http.Handler) http.Handler {
}
// Best-effort last-seen update. A failure here shouldn't fail the
// request; the session is still valid and this is observability.
if err := q.TouchSessionLastSeen(r.Context(), sess.ID); err != nil {
// last_ip rides the same UPDATE — a session whose address has
// moved since it was issued is the signal the active-sessions
// surface exists to show, and it costs nothing extra here.
if err := q.TouchSessionLastSeen(r.Context(), dbq.TouchSessionLastSeenParams{
ID: sess.ID,
LastIp: ClientIP(r),
}); err != nil {
slog.Warn("api: touch session last_seen failed", "err", err)
}
ctx := context.WithValue(r.Context(), userCtxKey, user)
ctx = context.WithValue(ctx, sessionIDCtxKey, sess.ID)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
@@ -112,6 +119,12 @@ func RequireUser(pool *pgxpool.Pool) func(http.Handler) http.Handler {
// middleware. Do not use this outside _test.go files.
func UserCtxKeyForTest() any { return userCtxKey }
// SessionIDCtxKeyForTest is the sibling of UserCtxKeyForTest for the session
// id, so handler tests can exercise the current-session logic (which row is
// "this device", which one logout-others must spare) without standing up the
// middleware. Do not use this outside _test.go files.
func SessionIDCtxKeyForTest() any { return sessionIDCtxKey }
// OptionalUser is RequireUser's permissive sibling: it resolves the caller
// from the session cookie or bearer header and attaches the user to context
// when present + valid, but does NOT 401 on absence. The downstream handler
@@ -153,6 +166,7 @@ func OptionalUser(pool *pgxpool.Pool, logger *slog.Logger) func(http.Handler) ht
return
}
ctx := context.WithValue(r.Context(), userCtxKey, user)
ctx = context.WithValue(ctx, sessionIDCtxKey, sess.ID)
next.ServeHTTP(w, r.WithContext(ctx))
})
}