1a7e130f9f
- Drop the FIFO from oauthStates: consumed states left entries behind, so an unrate-limited start/cancel cycle grew the slice without bound. Evict by oldest expiry instead — the map alone now bounds memory. - CreateSession runs INSERT + expiry sweep in one transaction. - slices.Contains replaces a hand-rolled contains; APIBase typo fixed. - Stale comments and test paths updated; login hover uses --ember-ink.
157 lines
4.7 KiB
Go
157 lines
4.7 KiB
Go
package session
|
|
|
|
import (
|
|
"crypto/rand"
|
|
"encoding/hex"
|
|
"net"
|
|
"net/http"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
const (
|
|
CookieName = "bmgr_session"
|
|
// 60 days: long enough that a phone stays logged in between reading spells.
|
|
SessionTTL = 60 * 24 * time.Hour
|
|
)
|
|
|
|
// NewID returns an opaque session id: 32 random bytes, hex-encoded. The id is
|
|
// all the cookie carries and all the sessions table keys on, so its entropy is
|
|
// what stops a guessed id from being someone else's session.
|
|
func NewID() string {
|
|
var b [32]byte
|
|
if _, err := rand.Read(b[:]); err != nil {
|
|
panic("session id: " + err.Error())
|
|
}
|
|
return hex.EncodeToString(b[:])
|
|
}
|
|
|
|
// isHTTPS reports whether the browser's connection is encrypted. Behind Traefik
|
|
// the Go server itself speaks plain HTTP, so the forwarded header is the only
|
|
// signal; without this check the Secure cookie would never be set in
|
|
// production, and setting it unconditionally would break http://localhost dev.
|
|
func isHTTPS(r *http.Request) bool {
|
|
return r.TLS != nil || r.Header.Get("X-Forwarded-Proto") == "https"
|
|
}
|
|
|
|
// SetCookie writes the session cookie. The value is the session id and nothing
|
|
// else; the row behind it is looked up on every request.
|
|
func SetCookie(w http.ResponseWriter, r *http.Request, id string) {
|
|
http.SetCookie(w, &http.Cookie{
|
|
Name: CookieName,
|
|
Value: id,
|
|
Path: "/",
|
|
MaxAge: int(SessionTTL / time.Second),
|
|
HttpOnly: true,
|
|
Secure: isHTTPS(r),
|
|
SameSite: http.SameSiteLaxMode,
|
|
})
|
|
}
|
|
|
|
func ClearCookie(w http.ResponseWriter, r *http.Request) {
|
|
http.SetCookie(w, &http.Cookie{
|
|
Name: CookieName,
|
|
Value: "",
|
|
Path: "/",
|
|
MaxAge: -1,
|
|
HttpOnly: true,
|
|
Secure: isHTTPS(r),
|
|
SameSite: http.SameSiteLaxMode,
|
|
})
|
|
}
|
|
|
|
const (
|
|
MaxFailures = 10
|
|
Window = 20 * time.Minute
|
|
)
|
|
|
|
// ClientIP returns the address the reverse proxy actually observed.
|
|
//
|
|
// Traefik appends the peer address to whatever X-Forwarded-For the client sent,
|
|
// so the leftmost entry is attacker-controlled and the rightmost is not. Go's
|
|
// Header.Get would only read the first header line, which a client can preempt
|
|
// by sending its own; Values covers every line so the true last hop is found.
|
|
// RemoteAddr is useless behind the proxy — it is always the Traefik container —
|
|
// so it serves only as the direct-connection fallback for local development.
|
|
func ClientIP(r *http.Request) string {
|
|
if vals := r.Header.Values("X-Forwarded-For"); len(vals) > 0 {
|
|
hops := strings.Split(vals[len(vals)-1], ",")
|
|
if ip := strings.TrimSpace(hops[len(hops)-1]); ip != "" {
|
|
return ip
|
|
}
|
|
}
|
|
host, _, err := net.SplitHostPort(r.RemoteAddr)
|
|
if err != nil {
|
|
return r.RemoteAddr
|
|
}
|
|
return host
|
|
}
|
|
|
|
// LoginLimiter throttles failed sign-in attempts: MaxFailures failures inside
|
|
// a rolling Window blocks further attempts from that IP until the oldest one
|
|
// ages out. There is no permanent ban and no unlock step.
|
|
//
|
|
// Behind carrier-grade NAT this budget is shared with every other subscriber on
|
|
// the same public address, so a stranger can lock the owner out for up to one
|
|
// window. That is accepted: the block self-heals, and ten attempts is generous
|
|
// for the occasional fumbled sign-in.
|
|
//
|
|
// State is in memory and per-process, so a restart clears it. Entries are
|
|
// pruned lazily on access; for a single-user deployment the map cannot grow
|
|
// past the handful of addresses that ever attempt a login.
|
|
type LoginLimiter struct {
|
|
mu sync.Mutex
|
|
failures map[string][]time.Time
|
|
}
|
|
|
|
func NewLoginLimiter() *LoginLimiter {
|
|
return &LoginLimiter{failures: make(map[string][]time.Time)}
|
|
}
|
|
|
|
// retryAfter returns how long ip must wait, or zero when it may try now.
|
|
func (l *LoginLimiter) RetryAfter(ip string, now time.Time) time.Duration {
|
|
l.mu.Lock()
|
|
defer l.mu.Unlock()
|
|
|
|
recent := l.pruneLocked(ip, now)
|
|
if len(recent) < MaxFailures {
|
|
return 0
|
|
}
|
|
return recent[0].Add(Window).Sub(now)
|
|
}
|
|
|
|
func (l *LoginLimiter) Fail(ip string, now time.Time) {
|
|
l.mu.Lock()
|
|
defer l.mu.Unlock()
|
|
l.failures[ip] = append(l.pruneLocked(ip, now), now)
|
|
}
|
|
|
|
func (l *LoginLimiter) Reset(ip string) {
|
|
l.mu.Lock()
|
|
defer l.mu.Unlock()
|
|
delete(l.failures, ip)
|
|
}
|
|
|
|
// pruneLocked drops attempts older than the window and returns what is left.
|
|
// The caller must hold l.mu.
|
|
func (l *LoginLimiter) pruneLocked(ip string, now time.Time) []time.Time {
|
|
cutoff := now.Add(-Window)
|
|
// In-place filter: kept reuses the backing array of the slice being
|
|
// ranged over. Safe to alias because append writes at index len(kept),
|
|
// which is always <= the range index i, and element i is read before
|
|
// that write — the write cursor can never overtake the read cursor.
|
|
kept := l.failures[ip][:0]
|
|
for _, at := range l.failures[ip] {
|
|
if at.After(cutoff) {
|
|
kept = append(kept, at)
|
|
}
|
|
}
|
|
if len(kept) == 0 {
|
|
delete(l.failures, ip)
|
|
return nil
|
|
}
|
|
l.failures[ip] = kept
|
|
return kept
|
|
}
|