Refactor load testing scripts to support Bash and PowerShell
- Updated README.md to reflect changes in load testing commands and added usage examples for Bash scripts. - Converted PowerShell load testing scripts to Bash equivalents for better cross-platform compatibility. - Added new Bash scripts: run-loadtests.sh, summarize-artillery.sh, and summarize-k6.sh to mirror existing PowerShell functionality. - Updated admin-api.js and ws-chat.yml for consistency and improved performance metrics reporting. - Enhanced error handling and output formatting in summary scripts for better readability.
This commit is contained in:
1 parent
9f60087a4c
commit
33b6296c5e
82 files changed
+19682
-21133
No files matched your search
+206
-206
@@ -1,207 +1,207 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// SessionStore manages admin authentication sessions.
|
||||
type SessionStore struct {
|
||||
mu sync.Mutex
|
||||
sessions map[string]time.Time
|
||||
}
|
||||
|
||||
// NewSessionStore creates a new session store.
|
||||
func NewSessionStore() *SessionStore {
|
||||
return &SessionStore{
|
||||
sessions: make(map[string]time.Time),
|
||||
}
|
||||
}
|
||||
|
||||
// GenerateToken creates a cryptographically random 64-char hex session token.
|
||||
func GenerateToken() (string, error) {
|
||||
buf := make([]byte, 32)
|
||||
if _, err := rand.Read(buf); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return hex.EncodeToString(buf), nil
|
||||
}
|
||||
|
||||
// Validate checks if a session token is valid and not expired.
|
||||
// Returns true if valid, false otherwise. Expired sessions are cleaned up.
|
||||
func (s *SessionStore) Validate(token string) bool {
|
||||
if token == "" {
|
||||
return false
|
||||
}
|
||||
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
expiresAt, ok := s.sessions[token]
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
if time.Now().After(expiresAt) {
|
||||
delete(s.sessions, token)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// Add stores a session token with expiry.
|
||||
func (s *SessionStore) Add(token string, expiresAt time.Time) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.sessions[token] = expiresAt
|
||||
}
|
||||
|
||||
// Remove deletes a session token.
|
||||
func (s *SessionStore) Remove(token string) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
delete(s.sessions, token)
|
||||
}
|
||||
|
||||
// CountActive returns the number of unexpired sessions.
|
||||
func (s *SessionStore) CountActive() int {
|
||||
now := time.Now()
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
for token, expiresAt := range s.sessions {
|
||||
if now.After(expiresAt) {
|
||||
delete(s.sessions, token)
|
||||
}
|
||||
}
|
||||
return len(s.sessions)
|
||||
}
|
||||
|
||||
// CookieSecure determines if the session cookie should have Secure flag.
|
||||
func CookieSecure(r *http.Request) bool {
|
||||
if forwardedProto := strings.TrimSpace(r.Header.Get("X-Forwarded-Proto")); forwardedProto != "" {
|
||||
return strings.EqualFold(forwardedProto, "https")
|
||||
}
|
||||
return r.TLS != nil
|
||||
}
|
||||
|
||||
// SameSiteForUserCookie returns the SameSite policy for the viewer session cookie.
|
||||
// Over HTTPS it returns SameSite=None so the cookie is sent cross-site from the
|
||||
// Workers-served SPA; over plain HTTP (local dev) it falls back to Lax.
|
||||
func SameSiteForUserCookie(r *http.Request) http.SameSite {
|
||||
if CookieSecure(r) {
|
||||
return http.SameSiteNoneMode
|
||||
}
|
||||
return http.SameSiteLaxMode
|
||||
}
|
||||
|
||||
// SetCookie writes a session cookie with the given SameSite policy.
|
||||
// SameSite=None is only valid together with Secure, which is enforced here.
|
||||
func SetCookie(w http.ResponseWriter, r *http.Request, cookieName, token string, expiresAt time.Time, sameSite http.SameSite) {
|
||||
secure := CookieSecure(r)
|
||||
if sameSite == http.SameSiteNoneMode {
|
||||
secure = true
|
||||
}
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: cookieName,
|
||||
Value: token,
|
||||
Path: "/",
|
||||
HttpOnly: true,
|
||||
SameSite: sameSite,
|
||||
Secure: secure,
|
||||
Expires: expiresAt,
|
||||
MaxAge: int(time.Until(expiresAt).Seconds()),
|
||||
})
|
||||
}
|
||||
|
||||
// ClearCookie removes a session cookie with the given SameSite policy.
|
||||
func ClearCookie(w http.ResponseWriter, r *http.Request, cookieName string, sameSite http.SameSite) {
|
||||
secure := CookieSecure(r)
|
||||
if sameSite == http.SameSiteNoneMode {
|
||||
secure = true
|
||||
}
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: cookieName,
|
||||
Value: "",
|
||||
Path: "/",
|
||||
HttpOnly: true,
|
||||
SameSite: sameSite,
|
||||
Secure: secure,
|
||||
Expires: time.Unix(0, 0),
|
||||
MaxAge: -1,
|
||||
})
|
||||
}
|
||||
|
||||
// GetTokenFromCookie extracts the session token from the request cookie.
|
||||
func GetTokenFromCookie(r *http.Request, cookieName string) (string, bool) {
|
||||
cookie, err := r.Cookie(cookieName)
|
||||
if err != nil || cookie.Value == "" {
|
||||
return "", false
|
||||
}
|
||||
return cookie.Value, true
|
||||
}
|
||||
|
||||
// RequireAdmin returns middleware that checks for a valid admin session.
|
||||
func RequireAdmin(store *SessionStore, cookieName string) func(http.HandlerFunc) http.HandlerFunc {
|
||||
return func(next http.HandlerFunc) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
token, ok := GetTokenFromCookie(r, cookieName)
|
||||
if !ok || !store.Validate(token) {
|
||||
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
next(w, r)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// UserSessionStore maps user session tokens to usernames with expiry.
|
||||
type UserSessionStore struct {
|
||||
mu sync.Mutex
|
||||
sessions map[string]userSession
|
||||
}
|
||||
|
||||
type userSession struct {
|
||||
Username string
|
||||
ExpiresAt time.Time
|
||||
}
|
||||
|
||||
// NewUserSessionStore creates a new user session store.
|
||||
func NewUserSessionStore() *UserSessionStore {
|
||||
return &UserSessionStore{sessions: make(map[string]userSession)}
|
||||
}
|
||||
|
||||
// Add stores a user session token with username and expiry.
|
||||
func (s *UserSessionStore) Add(token, username string, expiresAt time.Time) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.sessions[token] = userSession{Username: username, ExpiresAt: expiresAt}
|
||||
}
|
||||
|
||||
// Username returns the username for a valid, unexpired token.
|
||||
func (s *UserSessionStore) Username(token string) (string, bool) {
|
||||
if token == "" {
|
||||
return "", false
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
sess, ok := s.sessions[token]
|
||||
if !ok {
|
||||
return "", false
|
||||
}
|
||||
if time.Now().After(sess.ExpiresAt) {
|
||||
delete(s.sessions, token)
|
||||
return "", false
|
||||
}
|
||||
return sess.Username, true
|
||||
}
|
||||
|
||||
// Remove deletes a user session token.
|
||||
func (s *UserSessionStore) Remove(token string) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
delete(s.sessions, token)
|
||||
package auth
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// SessionStore manages admin authentication sessions.
|
||||
type SessionStore struct {
|
||||
mu sync.Mutex
|
||||
sessions map[string]time.Time
|
||||
}
|
||||
|
||||
// NewSessionStore creates a new session store.
|
||||
func NewSessionStore() *SessionStore {
|
||||
return &SessionStore{
|
||||
sessions: make(map[string]time.Time),
|
||||
}
|
||||
}
|
||||
|
||||
// GenerateToken creates a cryptographically random 64-char hex session token.
|
||||
func GenerateToken() (string, error) {
|
||||
buf := make([]byte, 32)
|
||||
if _, err := rand.Read(buf); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return hex.EncodeToString(buf), nil
|
||||
}
|
||||
|
||||
// Validate checks if a session token is valid and not expired.
|
||||
// Returns true if valid, false otherwise. Expired sessions are cleaned up.
|
||||
func (s *SessionStore) Validate(token string) bool {
|
||||
if token == "" {
|
||||
return false
|
||||
}
|
||||
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
expiresAt, ok := s.sessions[token]
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
if time.Now().After(expiresAt) {
|
||||
delete(s.sessions, token)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// Add stores a session token with expiry.
|
||||
func (s *SessionStore) Add(token string, expiresAt time.Time) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.sessions[token] = expiresAt
|
||||
}
|
||||
|
||||
// Remove deletes a session token.
|
||||
func (s *SessionStore) Remove(token string) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
delete(s.sessions, token)
|
||||
}
|
||||
|
||||
// CountActive returns the number of unexpired sessions.
|
||||
func (s *SessionStore) CountActive() int {
|
||||
now := time.Now()
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
for token, expiresAt := range s.sessions {
|
||||
if now.After(expiresAt) {
|
||||
delete(s.sessions, token)
|
||||
}
|
||||
}
|
||||
return len(s.sessions)
|
||||
}
|
||||
|
||||
// CookieSecure determines if the session cookie should have Secure flag.
|
||||
func CookieSecure(r *http.Request) bool {
|
||||
if forwardedProto := strings.TrimSpace(r.Header.Get("X-Forwarded-Proto")); forwardedProto != "" {
|
||||
return strings.EqualFold(forwardedProto, "https")
|
||||
}
|
||||
return r.TLS != nil
|
||||
}
|
||||
|
||||
// SameSiteForUserCookie returns the SameSite policy for the viewer session cookie.
|
||||
// Over HTTPS it returns SameSite=None so the cookie is sent cross-site from the
|
||||
// Workers-served SPA; over plain HTTP (local dev) it falls back to Lax.
|
||||
func SameSiteForUserCookie(r *http.Request) http.SameSite {
|
||||
if CookieSecure(r) {
|
||||
return http.SameSiteNoneMode
|
||||
}
|
||||
return http.SameSiteLaxMode
|
||||
}
|
||||
|
||||
// SetCookie writes a session cookie with the given SameSite policy.
|
||||
// SameSite=None is only valid together with Secure, which is enforced here.
|
||||
func SetCookie(w http.ResponseWriter, r *http.Request, cookieName, token string, expiresAt time.Time, sameSite http.SameSite) {
|
||||
secure := CookieSecure(r)
|
||||
if sameSite == http.SameSiteNoneMode {
|
||||
secure = true
|
||||
}
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: cookieName,
|
||||
Value: token,
|
||||
Path: "/",
|
||||
HttpOnly: true,
|
||||
SameSite: sameSite,
|
||||
Secure: secure,
|
||||
Expires: expiresAt,
|
||||
MaxAge: int(time.Until(expiresAt).Seconds()),
|
||||
})
|
||||
}
|
||||
|
||||
// ClearCookie removes a session cookie with the given SameSite policy.
|
||||
func ClearCookie(w http.ResponseWriter, r *http.Request, cookieName string, sameSite http.SameSite) {
|
||||
secure := CookieSecure(r)
|
||||
if sameSite == http.SameSiteNoneMode {
|
||||
secure = true
|
||||
}
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: cookieName,
|
||||
Value: "",
|
||||
Path: "/",
|
||||
HttpOnly: true,
|
||||
SameSite: sameSite,
|
||||
Secure: secure,
|
||||
Expires: time.Unix(0, 0),
|
||||
MaxAge: -1,
|
||||
})
|
||||
}
|
||||
|
||||
// GetTokenFromCookie extracts the session token from the request cookie.
|
||||
func GetTokenFromCookie(r *http.Request, cookieName string) (string, bool) {
|
||||
cookie, err := r.Cookie(cookieName)
|
||||
if err != nil || cookie.Value == "" {
|
||||
return "", false
|
||||
}
|
||||
return cookie.Value, true
|
||||
}
|
||||
|
||||
// RequireAdmin returns middleware that checks for a valid admin session.
|
||||
func RequireAdmin(store *SessionStore, cookieName string) func(http.HandlerFunc) http.HandlerFunc {
|
||||
return func(next http.HandlerFunc) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
token, ok := GetTokenFromCookie(r, cookieName)
|
||||
if !ok || !store.Validate(token) {
|
||||
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
next(w, r)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// UserSessionStore maps user session tokens to usernames with expiry.
|
||||
type UserSessionStore struct {
|
||||
mu sync.Mutex
|
||||
sessions map[string]userSession
|
||||
}
|
||||
|
||||
type userSession struct {
|
||||
Username string
|
||||
ExpiresAt time.Time
|
||||
}
|
||||
|
||||
// NewUserSessionStore creates a new user session store.
|
||||
func NewUserSessionStore() *UserSessionStore {
|
||||
return &UserSessionStore{sessions: make(map[string]userSession)}
|
||||
}
|
||||
|
||||
// Add stores a user session token with username and expiry.
|
||||
func (s *UserSessionStore) Add(token, username string, expiresAt time.Time) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.sessions[token] = userSession{Username: username, ExpiresAt: expiresAt}
|
||||
}
|
||||
|
||||
// Username returns the username for a valid, unexpired token.
|
||||
func (s *UserSessionStore) Username(token string) (string, bool) {
|
||||
if token == "" {
|
||||
return "", false
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
sess, ok := s.sessions[token]
|
||||
if !ok {
|
||||
return "", false
|
||||
}
|
||||
if time.Now().After(sess.ExpiresAt) {
|
||||
delete(s.sessions, token)
|
||||
return "", false
|
||||
}
|
||||
return sess.Username, true
|
||||
}
|
||||
|
||||
// Remove deletes a user session token.
|
||||
func (s *UserSessionStore) Remove(token string) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
delete(s.sessions, token)
|
||||
}
|
||||
+308
-308
@@ -1,309 +1,309 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestGenerateToken(t *testing.T) {
|
||||
token, err := GenerateToken()
|
||||
if err != nil {
|
||||
t.Fatalf("GenerateToken() error = %v", err)
|
||||
}
|
||||
if len(token) != 64 {
|
||||
t.Errorf("GenerateToken() length = %d, want 64", len(token))
|
||||
}
|
||||
|
||||
// Uniqueness check
|
||||
tokens := make(map[string]bool)
|
||||
for i := 0; i < 1000; i++ {
|
||||
tok, err := GenerateToken()
|
||||
if err != nil {
|
||||
t.Fatalf("GenerateToken() iteration %d error = %v", i, err)
|
||||
}
|
||||
if tokens[tok] {
|
||||
t.Errorf("GenerateToken() produced duplicate token at iteration %d", i)
|
||||
}
|
||||
tokens[tok] = true
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionStore_Validate(t *testing.T) {
|
||||
store := NewSessionStore()
|
||||
|
||||
// Empty token
|
||||
if store.Validate("") {
|
||||
t.Error("Validate(\"\") = true, want false")
|
||||
}
|
||||
|
||||
// Missing token
|
||||
if store.Validate("nonexistent") {
|
||||
t.Error("Validate(\"nonexistent\") = true, want false")
|
||||
}
|
||||
|
||||
// Valid token
|
||||
token, _ := GenerateToken()
|
||||
store.Add(token, time.Now().Add(1*time.Hour))
|
||||
if !store.Validate(token) {
|
||||
t.Error("Validate(valid) = false, want true")
|
||||
}
|
||||
|
||||
// Expired token
|
||||
expiredToken, _ := GenerateToken()
|
||||
store.Add(expiredToken, time.Now().Add(-1*time.Hour))
|
||||
if store.Validate(expiredToken) {
|
||||
t.Error("Validate(expired) = true, want false")
|
||||
}
|
||||
|
||||
// Expired token should be cleaned up
|
||||
if store.Validate(expiredToken) {
|
||||
t.Error("Validate(expired) second call = true, want false (should be cleaned)")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionStore_AddRemove(t *testing.T) {
|
||||
store := NewSessionStore()
|
||||
token, _ := GenerateToken()
|
||||
|
||||
store.Add(token, time.Now().Add(1*time.Hour))
|
||||
if !store.Validate(token) {
|
||||
t.Error("Validate after Add = false, want true")
|
||||
}
|
||||
|
||||
store.Remove(token)
|
||||
if store.Validate(token) {
|
||||
t.Error("Validate after Remove = true, want false")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionStore_CountActive(t *testing.T) {
|
||||
store := NewSessionStore()
|
||||
|
||||
if count := store.CountActive(); count != 0 {
|
||||
t.Errorf("CountActive() = %d, want 0", count)
|
||||
}
|
||||
|
||||
t1, _ := GenerateToken()
|
||||
t2, _ := GenerateToken()
|
||||
t3, _ := GenerateToken()
|
||||
|
||||
store.Add(t1, time.Now().Add(1*time.Hour))
|
||||
store.Add(t2, time.Now().Add(1*time.Hour))
|
||||
store.Add(t3, time.Now().Add(-1*time.Hour)) // expired
|
||||
|
||||
if count := store.CountActive(); count != 2 {
|
||||
t.Errorf("CountActive() = %d, want 2 (expired should be cleaned)", count)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCookieSecure(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
forwardedProto string
|
||||
tls bool
|
||||
expected bool
|
||||
}{
|
||||
{"https forwarded", "https", false, true},
|
||||
{"http forwarded", "http", false, false},
|
||||
{"empty forwarded, no TLS", "", false, false},
|
||||
{"empty forwarded, TLS", "", true, true},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
req := httptest.NewRequest("GET", "/", nil)
|
||||
if tt.forwardedProto != "" {
|
||||
req.Header.Set("X-Forwarded-Proto", tt.forwardedProto)
|
||||
}
|
||||
if tt.tls {
|
||||
req.TLS = &tls.ConnectionState{}
|
||||
}
|
||||
if got := CookieSecure(req); got != tt.expected {
|
||||
t.Errorf("CookieSecure() = %v, want %v", got, tt.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetCookie(t *testing.T) {
|
||||
req := httptest.NewRequest("GET", "/", nil)
|
||||
req.Header.Set("X-Forwarded-Proto", "https")
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
expiresAt := time.Now().Add(1 * time.Hour)
|
||||
SetCookie(w, req, "test_cookie", "abc123", expiresAt, http.SameSiteStrictMode)
|
||||
|
||||
cookies := w.Result().Cookies()
|
||||
if len(cookies) != 1 {
|
||||
t.Fatalf("expected 1 cookie, got %d", len(cookies))
|
||||
}
|
||||
c := cookies[0]
|
||||
if c.Name != "test_cookie" {
|
||||
t.Errorf("cookie name = %q, want test_cookie", c.Name)
|
||||
}
|
||||
if c.Value != "abc123" {
|
||||
t.Errorf("cookie value = %q, want abc123", c.Value)
|
||||
}
|
||||
if !c.HttpOnly {
|
||||
t.Error("cookie HttpOnly = false, want true")
|
||||
}
|
||||
if c.SameSite != http.SameSiteStrictMode {
|
||||
t.Errorf("cookie SameSite = %v, want Strict", c.SameSite)
|
||||
}
|
||||
if !c.Secure {
|
||||
t.Error("cookie Secure = false, want true (X-Forwarded-Proto: https)")
|
||||
}
|
||||
if c.Path != "/" {
|
||||
t.Errorf("cookie Path = %q, want /", c.Path)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClearCookie(t *testing.T) {
|
||||
req := httptest.NewRequest("GET", "/", nil)
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
ClearCookie(w, req, "test_cookie", http.SameSiteStrictMode)
|
||||
|
||||
cookies := w.Result().Cookies()
|
||||
if len(cookies) != 1 {
|
||||
t.Fatalf("expected 1 cookie, got %d", len(cookies))
|
||||
}
|
||||
c := cookies[0]
|
||||
if c.Name != "test_cookie" {
|
||||
t.Errorf("cookie name = %q, want test_cookie", c.Name)
|
||||
}
|
||||
if c.Value != "" {
|
||||
t.Errorf("cookie value = %q, want empty", c.Value)
|
||||
}
|
||||
if c.MaxAge != -1 {
|
||||
t.Errorf("cookie MaxAge = %d, want -1", c.MaxAge)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSameSiteForUserCookie(t *testing.T) {
|
||||
req := httptest.NewRequest("GET", "/", nil)
|
||||
req.Header.Set("X-Forwarded-Proto", "https")
|
||||
if got := SameSiteForUserCookie(req); got != http.SameSiteNoneMode {
|
||||
t.Errorf("SameSiteForUserCookie(https) = %v, want None", got)
|
||||
}
|
||||
|
||||
req2 := httptest.NewRequest("GET", "/", nil)
|
||||
if got := SameSiteForUserCookie(req2); got != http.SameSiteLaxMode {
|
||||
t.Errorf("SameSiteForUserCookie(http) = %v, want Lax", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetCookie_NoneForcesSecure(t *testing.T) {
|
||||
req := httptest.NewRequest("GET", "/", nil)
|
||||
w := httptest.NewRecorder()
|
||||
expiresAt := time.Now().Add(1 * time.Hour)
|
||||
SetCookie(w, req, "test_cookie", "abc123", expiresAt, http.SameSiteNoneMode)
|
||||
|
||||
cookies := w.Result().Cookies()
|
||||
if len(cookies) != 1 {
|
||||
t.Fatalf("expected 1 cookie, got %d", len(cookies))
|
||||
}
|
||||
c := cookies[0]
|
||||
if c.SameSite != http.SameSiteNoneMode {
|
||||
t.Errorf("cookie SameSite = %v, want None", c.SameSite)
|
||||
}
|
||||
if !c.Secure {
|
||||
t.Error("cookie Secure = false, want true (SameSite=None requires Secure)")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetTokenFromCookie(t *testing.T) {
|
||||
req := httptest.NewRequest("GET", "/", nil)
|
||||
req.AddCookie(&http.Cookie{Name: "session", Value: "token123"})
|
||||
|
||||
token, ok := GetTokenFromCookie(req, "session")
|
||||
if !ok {
|
||||
t.Error("GetTokenFromCookie() ok = false, want true")
|
||||
}
|
||||
if token != "token123" {
|
||||
t.Errorf("GetTokenFromCookie() = %q, want token123", token)
|
||||
}
|
||||
|
||||
// Missing cookie
|
||||
_, ok = GetTokenFromCookie(req, "nonexistent")
|
||||
if ok {
|
||||
t.Error("GetTokenFromCookie() for missing cookie ok = true, want false")
|
||||
}
|
||||
|
||||
// Empty value
|
||||
req2 := httptest.NewRequest("GET", "/", nil)
|
||||
req2.AddCookie(&http.Cookie{Name: "session", Value: ""})
|
||||
_, ok = GetTokenFromCookie(req2, "session")
|
||||
if ok {
|
||||
t.Error("GetTokenFromCookie() for empty value ok = true, want false")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRequireAdmin(t *testing.T) {
|
||||
store := NewSessionStore()
|
||||
token, _ := GenerateToken()
|
||||
store.Add(token, time.Now().Add(1*time.Hour))
|
||||
|
||||
handler := RequireAdmin(store, "session")(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write([]byte("ok"))
|
||||
})
|
||||
|
||||
// Valid session
|
||||
req := httptest.NewRequest("GET", "/", nil)
|
||||
req.AddCookie(&http.Cookie{Name: "session", Value: token})
|
||||
w := httptest.NewRecorder()
|
||||
handler(w, req)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Errorf("status = %d, want 200", w.Code)
|
||||
}
|
||||
|
||||
// No cookie
|
||||
req2 := httptest.NewRequest("GET", "/", nil)
|
||||
w2 := httptest.NewRecorder()
|
||||
handler(w2, req2)
|
||||
if w2.Code != http.StatusUnauthorized {
|
||||
t.Errorf("status = %d, want 401", w2.Code)
|
||||
}
|
||||
|
||||
// Invalid token
|
||||
req3 := httptest.NewRequest("GET", "/", nil)
|
||||
req3.AddCookie(&http.Cookie{Name: "session", Value: "invalid"})
|
||||
w3 := httptest.NewRecorder()
|
||||
handler(w3, req3)
|
||||
if w3.Code != http.StatusUnauthorized {
|
||||
t.Errorf("status = %d, want 401", w3.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUserSessionStore(t *testing.T) {
|
||||
store := NewUserSessionStore()
|
||||
|
||||
if _, ok := store.Username(""); ok {
|
||||
t.Error("Username(\"\") = true, want false")
|
||||
}
|
||||
|
||||
token, _ := GenerateToken()
|
||||
store.Add(token, "alice", time.Now().Add(1*time.Hour))
|
||||
|
||||
username, ok := store.Username(token)
|
||||
if !ok || username != "alice" {
|
||||
t.Errorf("Username() = %q, %v; want alice, true", username, ok)
|
||||
}
|
||||
|
||||
// Expired session
|
||||
expired, _ := GenerateToken()
|
||||
store.Add(expired, "bob", time.Now().Add(-1*time.Hour))
|
||||
if _, ok := store.Username(expired); ok {
|
||||
t.Error("Username(expired) = true, want false")
|
||||
}
|
||||
|
||||
// Remove
|
||||
store.Remove(token)
|
||||
if _, ok := store.Username(token); ok {
|
||||
t.Error("Username after Remove = true, want false")
|
||||
}
|
||||
package auth
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestGenerateToken(t *testing.T) {
|
||||
token, err := GenerateToken()
|
||||
if err != nil {
|
||||
t.Fatalf("GenerateToken() error = %v", err)
|
||||
}
|
||||
if len(token) != 64 {
|
||||
t.Errorf("GenerateToken() length = %d, want 64", len(token))
|
||||
}
|
||||
|
||||
// Uniqueness check
|
||||
tokens := make(map[string]bool)
|
||||
for i := 0; i < 1000; i++ {
|
||||
tok, err := GenerateToken()
|
||||
if err != nil {
|
||||
t.Fatalf("GenerateToken() iteration %d error = %v", i, err)
|
||||
}
|
||||
if tokens[tok] {
|
||||
t.Errorf("GenerateToken() produced duplicate token at iteration %d", i)
|
||||
}
|
||||
tokens[tok] = true
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionStore_Validate(t *testing.T) {
|
||||
store := NewSessionStore()
|
||||
|
||||
// Empty token
|
||||
if store.Validate("") {
|
||||
t.Error("Validate(\"\") = true, want false")
|
||||
}
|
||||
|
||||
// Missing token
|
||||
if store.Validate("nonexistent") {
|
||||
t.Error("Validate(\"nonexistent\") = true, want false")
|
||||
}
|
||||
|
||||
// Valid token
|
||||
token, _ := GenerateToken()
|
||||
store.Add(token, time.Now().Add(1*time.Hour))
|
||||
if !store.Validate(token) {
|
||||
t.Error("Validate(valid) = false, want true")
|
||||
}
|
||||
|
||||
// Expired token
|
||||
expiredToken, _ := GenerateToken()
|
||||
store.Add(expiredToken, time.Now().Add(-1*time.Hour))
|
||||
if store.Validate(expiredToken) {
|
||||
t.Error("Validate(expired) = true, want false")
|
||||
}
|
||||
|
||||
// Expired token should be cleaned up
|
||||
if store.Validate(expiredToken) {
|
||||
t.Error("Validate(expired) second call = true, want false (should be cleaned)")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionStore_AddRemove(t *testing.T) {
|
||||
store := NewSessionStore()
|
||||
token, _ := GenerateToken()
|
||||
|
||||
store.Add(token, time.Now().Add(1*time.Hour))
|
||||
if !store.Validate(token) {
|
||||
t.Error("Validate after Add = false, want true")
|
||||
}
|
||||
|
||||
store.Remove(token)
|
||||
if store.Validate(token) {
|
||||
t.Error("Validate after Remove = true, want false")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionStore_CountActive(t *testing.T) {
|
||||
store := NewSessionStore()
|
||||
|
||||
if count := store.CountActive(); count != 0 {
|
||||
t.Errorf("CountActive() = %d, want 0", count)
|
||||
}
|
||||
|
||||
t1, _ := GenerateToken()
|
||||
t2, _ := GenerateToken()
|
||||
t3, _ := GenerateToken()
|
||||
|
||||
store.Add(t1, time.Now().Add(1*time.Hour))
|
||||
store.Add(t2, time.Now().Add(1*time.Hour))
|
||||
store.Add(t3, time.Now().Add(-1*time.Hour)) // expired
|
||||
|
||||
if count := store.CountActive(); count != 2 {
|
||||
t.Errorf("CountActive() = %d, want 2 (expired should be cleaned)", count)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCookieSecure(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
forwardedProto string
|
||||
tls bool
|
||||
expected bool
|
||||
}{
|
||||
{"https forwarded", "https", false, true},
|
||||
{"http forwarded", "http", false, false},
|
||||
{"empty forwarded, no TLS", "", false, false},
|
||||
{"empty forwarded, TLS", "", true, true},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
req := httptest.NewRequest("GET", "/", nil)
|
||||
if tt.forwardedProto != "" {
|
||||
req.Header.Set("X-Forwarded-Proto", tt.forwardedProto)
|
||||
}
|
||||
if tt.tls {
|
||||
req.TLS = &tls.ConnectionState{}
|
||||
}
|
||||
if got := CookieSecure(req); got != tt.expected {
|
||||
t.Errorf("CookieSecure() = %v, want %v", got, tt.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetCookie(t *testing.T) {
|
||||
req := httptest.NewRequest("GET", "/", nil)
|
||||
req.Header.Set("X-Forwarded-Proto", "https")
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
expiresAt := time.Now().Add(1 * time.Hour)
|
||||
SetCookie(w, req, "test_cookie", "abc123", expiresAt, http.SameSiteStrictMode)
|
||||
|
||||
cookies := w.Result().Cookies()
|
||||
if len(cookies) != 1 {
|
||||
t.Fatalf("expected 1 cookie, got %d", len(cookies))
|
||||
}
|
||||
c := cookies[0]
|
||||
if c.Name != "test_cookie" {
|
||||
t.Errorf("cookie name = %q, want test_cookie", c.Name)
|
||||
}
|
||||
if c.Value != "abc123" {
|
||||
t.Errorf("cookie value = %q, want abc123", c.Value)
|
||||
}
|
||||
if !c.HttpOnly {
|
||||
t.Error("cookie HttpOnly = false, want true")
|
||||
}
|
||||
if c.SameSite != http.SameSiteStrictMode {
|
||||
t.Errorf("cookie SameSite = %v, want Strict", c.SameSite)
|
||||
}
|
||||
if !c.Secure {
|
||||
t.Error("cookie Secure = false, want true (X-Forwarded-Proto: https)")
|
||||
}
|
||||
if c.Path != "/" {
|
||||
t.Errorf("cookie Path = %q, want /", c.Path)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClearCookie(t *testing.T) {
|
||||
req := httptest.NewRequest("GET", "/", nil)
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
ClearCookie(w, req, "test_cookie", http.SameSiteStrictMode)
|
||||
|
||||
cookies := w.Result().Cookies()
|
||||
if len(cookies) != 1 {
|
||||
t.Fatalf("expected 1 cookie, got %d", len(cookies))
|
||||
}
|
||||
c := cookies[0]
|
||||
if c.Name != "test_cookie" {
|
||||
t.Errorf("cookie name = %q, want test_cookie", c.Name)
|
||||
}
|
||||
if c.Value != "" {
|
||||
t.Errorf("cookie value = %q, want empty", c.Value)
|
||||
}
|
||||
if c.MaxAge != -1 {
|
||||
t.Errorf("cookie MaxAge = %d, want -1", c.MaxAge)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSameSiteForUserCookie(t *testing.T) {
|
||||
req := httptest.NewRequest("GET", "/", nil)
|
||||
req.Header.Set("X-Forwarded-Proto", "https")
|
||||
if got := SameSiteForUserCookie(req); got != http.SameSiteNoneMode {
|
||||
t.Errorf("SameSiteForUserCookie(https) = %v, want None", got)
|
||||
}
|
||||
|
||||
req2 := httptest.NewRequest("GET", "/", nil)
|
||||
if got := SameSiteForUserCookie(req2); got != http.SameSiteLaxMode {
|
||||
t.Errorf("SameSiteForUserCookie(http) = %v, want Lax", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetCookie_NoneForcesSecure(t *testing.T) {
|
||||
req := httptest.NewRequest("GET", "/", nil)
|
||||
w := httptest.NewRecorder()
|
||||
expiresAt := time.Now().Add(1 * time.Hour)
|
||||
SetCookie(w, req, "test_cookie", "abc123", expiresAt, http.SameSiteNoneMode)
|
||||
|
||||
cookies := w.Result().Cookies()
|
||||
if len(cookies) != 1 {
|
||||
t.Fatalf("expected 1 cookie, got %d", len(cookies))
|
||||
}
|
||||
c := cookies[0]
|
||||
if c.SameSite != http.SameSiteNoneMode {
|
||||
t.Errorf("cookie SameSite = %v, want None", c.SameSite)
|
||||
}
|
||||
if !c.Secure {
|
||||
t.Error("cookie Secure = false, want true (SameSite=None requires Secure)")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetTokenFromCookie(t *testing.T) {
|
||||
req := httptest.NewRequest("GET", "/", nil)
|
||||
req.AddCookie(&http.Cookie{Name: "session", Value: "token123"})
|
||||
|
||||
token, ok := GetTokenFromCookie(req, "session")
|
||||
if !ok {
|
||||
t.Error("GetTokenFromCookie() ok = false, want true")
|
||||
}
|
||||
if token != "token123" {
|
||||
t.Errorf("GetTokenFromCookie() = %q, want token123", token)
|
||||
}
|
||||
|
||||
// Missing cookie
|
||||
_, ok = GetTokenFromCookie(req, "nonexistent")
|
||||
if ok {
|
||||
t.Error("GetTokenFromCookie() for missing cookie ok = true, want false")
|
||||
}
|
||||
|
||||
// Empty value
|
||||
req2 := httptest.NewRequest("GET", "/", nil)
|
||||
req2.AddCookie(&http.Cookie{Name: "session", Value: ""})
|
||||
_, ok = GetTokenFromCookie(req2, "session")
|
||||
if ok {
|
||||
t.Error("GetTokenFromCookie() for empty value ok = true, want false")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRequireAdmin(t *testing.T) {
|
||||
store := NewSessionStore()
|
||||
token, _ := GenerateToken()
|
||||
store.Add(token, time.Now().Add(1*time.Hour))
|
||||
|
||||
handler := RequireAdmin(store, "session")(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write([]byte("ok"))
|
||||
})
|
||||
|
||||
// Valid session
|
||||
req := httptest.NewRequest("GET", "/", nil)
|
||||
req.AddCookie(&http.Cookie{Name: "session", Value: token})
|
||||
w := httptest.NewRecorder()
|
||||
handler(w, req)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Errorf("status = %d, want 200", w.Code)
|
||||
}
|
||||
|
||||
// No cookie
|
||||
req2 := httptest.NewRequest("GET", "/", nil)
|
||||
w2 := httptest.NewRecorder()
|
||||
handler(w2, req2)
|
||||
if w2.Code != http.StatusUnauthorized {
|
||||
t.Errorf("status = %d, want 401", w2.Code)
|
||||
}
|
||||
|
||||
// Invalid token
|
||||
req3 := httptest.NewRequest("GET", "/", nil)
|
||||
req3.AddCookie(&http.Cookie{Name: "session", Value: "invalid"})
|
||||
w3 := httptest.NewRecorder()
|
||||
handler(w3, req3)
|
||||
if w3.Code != http.StatusUnauthorized {
|
||||
t.Errorf("status = %d, want 401", w3.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUserSessionStore(t *testing.T) {
|
||||
store := NewUserSessionStore()
|
||||
|
||||
if _, ok := store.Username(""); ok {
|
||||
t.Error("Username(\"\") = true, want false")
|
||||
}
|
||||
|
||||
token, _ := GenerateToken()
|
||||
store.Add(token, "alice", time.Now().Add(1*time.Hour))
|
||||
|
||||
username, ok := store.Username(token)
|
||||
if !ok || username != "alice" {
|
||||
t.Errorf("Username() = %q, %v; want alice, true", username, ok)
|
||||
}
|
||||
|
||||
// Expired session
|
||||
expired, _ := GenerateToken()
|
||||
store.Add(expired, "bob", time.Now().Add(-1*time.Hour))
|
||||
if _, ok := store.Username(expired); ok {
|
||||
t.Error("Username(expired) = true, want false")
|
||||
}
|
||||
|
||||
// Remove
|
||||
store.Remove(token)
|
||||
if _, ok := store.Username(token); ok {
|
||||
t.Error("Username after Remove = true, want false")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user