Nick Meslovich / Products / Gravitas

auth.go

8.7 KB · raw

package main

import (
	"crypto/hmac"
	"crypto/rand"
	"crypto/sha256"
	"crypto/subtle"
	"encoding/hex"
	"fmt"
	"net"
	"net/http"
	"net/url"
	"strconv"
	"strings"
	"sync"
	"time"
)

const (
	sessionCookieName = "gravitas_session"
	sessionSalt       = "gravitas-session-v1"
	pbkdf2Iterations  = 120000
	pbkdf2KeyLen      = 32

	unlockWindow       = 5 * time.Minute
	maxUnlockFailures  = 10
	defaultSessionDays = 30
	minSessionDays     = 1
	maxSessionDays     = 365
)

type AuthManager struct {
	token      string
	sessionKey []byte

	mu          sync.Mutex
	sessionDays int
	failures    map[string][]time.Time
}

func NewAuthManager(token string, sessionDays int) *AuthManager {
	if sessionDays < minSessionDays || sessionDays > maxSessionDays {
		sessionDays = defaultSessionDays
	}
	var key []byte
	if token != "" {
		key = pbkdf2SHA256([]byte(token), []byte(sessionSalt), pbkdf2Iterations, pbkdf2KeyLen)
	} else {
		key = make([]byte, 32)
		_, _ = rand.Read(key)
	}
	return &AuthManager{
		token:       token,
		sessionKey:  key,
		sessionDays: sessionDays,
		failures:    make(map[string][]time.Time),
	}
}

func (a *AuthManager) SessionDays() int {
	a.mu.Lock()
	defer a.mu.Unlock()
	return a.sessionDays
}

func (a *AuthManager) SetSessionDays(days int) int {
	if days < minSessionDays {
		days = minSessionDays
	}
	if days > maxSessionDays {
		days = maxSessionDays
	}
	a.mu.Lock()
	a.sessionDays = days
	a.mu.Unlock()
	return days
}

func (a *AuthManager) RequiresAuth() bool {
	return a.token != ""
}

func (a *AuthManager) VerifyToken(candidate string) bool {
	if a.token == "" {
		return true
	}
	if candidate == "" {
		return false
	}
	ca := sha256.Sum256([]byte(candidate))
	ta := sha256.Sum256([]byte(a.token))
	return subtle.ConstantTimeCompare(ca[:], ta[:]) == 1
}

func (a *AuthManager) SignCookieValue(expiresEpochSec int64) string {
	payload := strconv.FormatInt(expiresEpochSec, 10)
	mac := hmac.New(sha256.New, a.sessionKey)
	mac.Write([]byte("session:"))
	mac.Write([]byte(payload))
	sig := hex.EncodeToString(mac.Sum(nil))[:32]
	return payload + "." + sig
}

func (a *AuthManager) VerifyCookieValue(val string, now time.Time) (int64, bool) {
	if val == "" {
		return 0, false
	}
	dot := strings.IndexByte(val, '.')
	if dot <= 0 || dot >= len(val)-1 {
		return 0, false
	}
	expStr := val[:dot]
	sig := val[dot+1:]
	exp, err := strconv.ParseInt(expStr, 10, 64)
	if err != nil {
		return 0, false
	}
	if exp <= now.Unix() {
		return 0, false
	}
	expected := a.SignCookieValue(exp)
	expectedSig := expected[dot+1:]
	if len(sig) != len(expectedSig) {
		return 0, false
	}
	if subtle.ConstantTimeCompare([]byte(sig), []byte(expectedSig)) != 1 {
		return 0, false
	}
	return exp, true
}

func (a *AuthManager) CheckRequestAuth(r *http.Request) (authenticated bool, viaCookie bool, expiresAt int64) {
	if a.token == "" {
		return true, false, 0
	}
	// 1. Authorization: Bearer <token>
	authHeader := strings.TrimSpace(r.Header.Get("Authorization"))
	if strings.HasPrefix(strings.ToLower(authHeader), "bearer ") {
		tok := strings.TrimSpace(authHeader[7:])
		if a.VerifyToken(tok) {
			return true, false, 0
		}
	}
	// 2. X-Gravitas-Token header
	if tok := strings.TrimSpace(r.Header.Get("X-Gravitas-Token")); tok != "" {
		if a.VerifyToken(tok) {
			return true, false, 0
		}
	}
	// 3. Signed session cookie
	if c, err := r.Cookie(sessionCookieName); err == nil && c != nil {
		if exp, ok := a.VerifyCookieValue(c.Value, time.Now()); ok {
			return true, true, exp
		}
	}
	return false, false, 0
}

// hasHeaderToken reports whether the request presents a token via
// Authorization: Bearer or X-Gravitas-Token.
func hasHeaderToken(r *http.Request) bool {
	authHeader := strings.TrimSpace(r.Header.Get("Authorization"))
	if strings.HasPrefix(strings.ToLower(authHeader), "bearer ") && strings.TrimSpace(authHeader[7:]) != "" {
		return true
	}
	return strings.TrimSpace(r.Header.Get("X-Gravitas-Token")) != ""
}

// AuthenticateRequest is CheckRequestAuth with brute-force protection for
// header tokens: token guesses sent via Authorization / X-Gravitas-Token
// share the same per-IP failure budget as POST /api/unlock. While an IP is
// throttled, header tokens are not checked at all (a valid session cookie
// still works). retryAfter > 0 means the caller must answer 429.
func (a *AuthManager) AuthenticateRequest(r *http.Request, now time.Time) (authenticated bool, viaCookie bool, expiresAt int64, retryAfter int) {
	if a.token == "" || !hasHeaderToken(r) {
		authenticated, viaCookie, expiresAt = a.CheckRequestAuth(r)
		return authenticated, viaCookie, expiresAt, 0
	}
	ip := ClientIP(r)
	if allowed, retry := a.CheckRateLimit(ip, now); !allowed {
		if c, err := r.Cookie(sessionCookieName); err == nil && c != nil {
			if exp, ok := a.VerifyCookieValue(c.Value, now); ok {
				return true, true, exp, 0
			}
		}
		return false, false, 0, retry
	}
	authenticated, viaCookie, expiresAt = a.CheckRequestAuth(r)
	if !authenticated {
		if throttled, retry := a.RecordFailure(ip, now); throttled {
			return false, false, 0, retry
		}
	} else if !viaCookie {
		a.ClearFailures(ip)
	}
	return authenticated, viaCookie, expiresAt, 0
}

func (a *AuthManager) SetSessionCookie(w http.ResponseWriter, r *http.Request) (int64, int) {
	days := a.SessionDays()
	maxAge := days * 86400
	expiresAt := time.Now().Unix() + int64(maxAge)
	val := a.SignCookieValue(expiresAt)

	secure := r.TLS != nil || strings.EqualFold(r.Header.Get("X-Forwarded-Proto"), "https")
	cookie := fmt.Sprintf("%s=%s; Path=/; Max-Age=%d; HttpOnly; SameSite=Strict", sessionCookieName, val, maxAge)
	if secure {
		cookie += "; Secure"
	}
	w.Header().Add("Set-Cookie", cookie)
	return expiresAt, days
}

func (a *AuthManager) ClearSessionCookie(w http.ResponseWriter) {
	w.Header().Add("Set-Cookie", fmt.Sprintf("%s=; Path=/; Max-Age=0; HttpOnly; SameSite=Strict", sessionCookieName))
}

// CheckRateLimit checks if the client IP is currently throttled.
// Returns (allowed, retryAfterSeconds).
func (a *AuthManager) CheckRateLimit(ip string, now time.Time) (bool, int) {
	a.mu.Lock()
	defer a.mu.Unlock()
	a.pruneFailuresLocked(ip, now)
	list := a.failures[ip]
	if len(list) < maxUnlockFailures {
		return true, 0
	}
	oldest := list[0]
	retryAfter := int(oldest.Add(unlockWindow).Sub(now).Seconds()) + 1
	if retryAfter < 1 {
		retryAfter = 1
	}
	return false, retryAfter
}

func (a *AuthManager) RecordFailure(ip string, now time.Time) (bool, int) {
	a.mu.Lock()
	defer a.mu.Unlock()
	a.pruneFailuresLocked(ip, now)
	list := append(a.failures[ip], now)
	a.failures[ip] = list
	if len(list) >= maxUnlockFailures {
		oldest := list[0]
		retryAfter := int(oldest.Add(unlockWindow).Sub(now).Seconds()) + 1
		if retryAfter < 1 {
			retryAfter = 1
		}
		return true, retryAfter
	}
	return false, 0
}

func (a *AuthManager) ClearFailures(ip string) {
	a.mu.Lock()
	delete(a.failures, ip)
	a.mu.Unlock()
}

func (a *AuthManager) pruneFailuresLocked(ip string, now time.Time) {
	list := a.failures[ip]
	if len(list) == 0 {
		return
	}
	cutoff := now.Add(-unlockWindow)
	idx := 0
	for idx < len(list) && list[idx].Before(cutoff) {
		idx++
	}
	if idx == len(list) {
		delete(a.failures, ip)
	} else if idx > 0 {
		a.failures[ip] = list[idx:]
	}
}

func ClientIP(r *http.Request) string {
	host, _, err := net.SplitHostPort(r.RemoteAddr)
	if err != nil {
		return r.RemoteAddr
	}
	return host
}

func CheckSameOrigin(r *http.Request) bool {
	if r.Method == http.MethodGet || r.Method == http.MethodHead || r.Method == http.MethodOptions {
		return true
	}
	if secSite := r.Header.Get("Sec-Fetch-Site"); secSite != "" {
		if secSite != "same-origin" && secSite != "none" {
			return false
		}
	}
	origin := r.Header.Get("Origin")
	if origin == "" {
		return true
	}
	u, err := url.Parse(origin)
	if err != nil || u.Host == "" {
		return false
	}
	return strings.EqualFold(u.Host, r.Host)
}

func IsLoopbackHost(host string) bool {
	h := strings.TrimSpace(strings.ToLower(host))
	if h == "localhost" || h == "127.0.0.1" || h == "::1" || h == "[::1]" {
		return true
	}
	ip := net.ParseIP(strings.Trim(h, "[]"))
	return ip != nil && ip.IsLoopback()
}

// pbkdf2SHA256 implements RFC 2898 PBKDF2-HMAC-SHA256 using only the Go standard library.
func pbkdf2SHA256(password, salt []byte, iter, keyLen int) []byte {
	prf := func(key, data []byte) []byte {
		mac := hmac.New(sha256.New, key)
		mac.Write(data)
		return mac.Sum(nil)
	}
	hashLen := sha256.Size
	numBlocks := (keyLen + hashLen - 1) / hashLen
	var dk []byte
	for block := 1; block <= numBlocks; block++ {
		// U_1 = PRF(P, S || INT_32_BE(block))
		blockBytes := []byte{byte(block >> 24), byte(block >> 16), byte(block >> 8), byte(block)}
		u := prf(password, append(append([]byte{}, salt...), blockBytes...))
		t := make([]byte, len(u))
		copy(t, u)
		for i := 2; i <= iter; i++ {
			u = prf(password, u)
			for j := range t {
				t[j] ^= u[j]
			}
		}
		dk = append(dk, t...)
	}
	return dk[:keyLen]
}