forked from mtusi2026/mtusi2026lab3
139 lines
4.5 KiB
Go
139 lines
4.5 KiB
Go
package auth_tests
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"crypto/sha256"
|
|
"encoding/json"
|
|
"net/http"
|
|
"os"
|
|
"os/exec"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
)
|
|
|
|
func TestRedisHTTPFullRestartKeepsDeadlineAndRevocation(t *testing.T) {
|
|
base, hook := os.Getenv("AUTH_TEST_BASE_URL"), os.Getenv("AUTH_TEST_STACK_RESTART_HOOK")
|
|
if base == "" || hook == "" {
|
|
t.Skip("set AUTH_TEST_BASE_URL and AUTH_TEST_STACK_RESTART_HOOK for a disposable API+stores stack")
|
|
}
|
|
for _, withLogout := range []bool{false, true} {
|
|
name := "active_only"
|
|
if withLogout {
|
|
name = "active_and_revoked"
|
|
}
|
|
t.Run(name, func(t *testing.T) {
|
|
f := newRedisFixture(t)
|
|
ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)
|
|
defer cancel()
|
|
client := &http.Client{Timeout: 5 * time.Second}
|
|
waitReady := func() {
|
|
t.Helper()
|
|
deadline := time.Now().Add(15 * time.Second)
|
|
for time.Now().Before(deadline) {
|
|
response, err := client.Get(strings.TrimRight(base, "/") + "/health/ready")
|
|
if err == nil {
|
|
response.Body.Close()
|
|
if response.StatusCode == http.StatusOK {
|
|
return
|
|
}
|
|
}
|
|
time.Sleep(100 * time.Millisecond)
|
|
}
|
|
t.Fatal("API did not regain readiness after restart")
|
|
}
|
|
waitReady()
|
|
username := "restart_" + strings.ReplaceAll(uuid.NewString(), "-", "")[:18]
|
|
password := "Synthetic:" + uuid.NewString()
|
|
call := func(method, path, token string, body any, basic bool, want int, dst any) {
|
|
t.Helper()
|
|
var data bytes.Buffer
|
|
if body != nil {
|
|
if json.NewEncoder(&data).Encode(body) != nil {
|
|
t.Fatal("cannot encode test request")
|
|
}
|
|
}
|
|
req, err := http.NewRequestWithContext(ctx, method, strings.TrimRight(base, "/")+path, &data)
|
|
if err != nil {
|
|
t.Fatal("cannot construct test request")
|
|
}
|
|
if body != nil {
|
|
req.Header.Set("Content-Type", "application/json")
|
|
}
|
|
if basic {
|
|
req.SetBasicAuth(username, password)
|
|
} else if token != "" {
|
|
req.Header.Set("Authorization", "Bearer "+token)
|
|
}
|
|
response, err := client.Do(req)
|
|
if err != nil {
|
|
t.Fatal("restart HTTP request failed")
|
|
}
|
|
defer response.Body.Close()
|
|
if response.StatusCode != want {
|
|
t.Fatalf("%s %s: want %d, got %d", method, path, want, response.StatusCode)
|
|
}
|
|
if dst != nil && json.NewDecoder(response.Body).Decode(dst) != nil {
|
|
t.Fatal("invalid restart response JSON")
|
|
}
|
|
}
|
|
call("POST", "/api/v1/users", "", map[string]string{"username": username, "password": password, "display_name": "Restart fixture"}, false, 201, nil)
|
|
var active struct {
|
|
Token string `json:"token"`
|
|
ExpiresAt time.Time `json:"expires_at"`
|
|
}
|
|
call("POST", "/api/v1/auth/sessions", "", nil, true, 201, &active)
|
|
hash := f.track(active.Token)
|
|
before, err := f.repo.GetSessionByTokenHash(ctx, hash[:])
|
|
if err != nil {
|
|
t.Fatal("cannot inspect issued session")
|
|
}
|
|
if !before.ExpiresAt.Equal(active.ExpiresAt) {
|
|
t.Fatal("HTTP and Redis expiry differ")
|
|
}
|
|
remaining := f.client.PTTL(ctx, f.keys[0]).Val()
|
|
if remaining < 2*time.Minute {
|
|
t.Fatal("normal restart suite requires long session TTL")
|
|
}
|
|
revoked := ""
|
|
if withLogout {
|
|
var other struct {
|
|
Token string `json:"token"`
|
|
}
|
|
call("POST", "/api/v1/auth/sessions", "", nil, true, 201, &other)
|
|
revoked = other.Token
|
|
f.track(revoked)
|
|
call("DELETE", "/api/v1/auth/sessions/current", revoked, nil, false, 204, nil)
|
|
call("GET", "/api/v1/users/me", revoked, nil, false, 401, nil)
|
|
}
|
|
if exec.CommandContext(ctx, hook).Run() != nil {
|
|
t.Fatal("real API+stores restart hook failed")
|
|
}
|
|
waitReady()
|
|
call("GET", "/health/live", "", nil, false, 200, nil)
|
|
call("GET", "/health/ready", "", nil, false, 200, nil)
|
|
call("GET", "/api/v1/users/me", active.Token, nil, false, 200, nil)
|
|
after, err := f.repo.GetSessionByTokenHash(ctx, hash[:])
|
|
if err != nil {
|
|
t.Fatal("restart lost session")
|
|
}
|
|
if !after.ExpiresAt.Equal(before.ExpiresAt) || after.UserID != before.UserID || !after.CreatedAt.Equal(before.CreatedAt) {
|
|
t.Fatal("actual API+Redis restart changed session identity/deadline")
|
|
}
|
|
if ttl := f.client.PTTL(ctx, f.keys[0]).Val(); ttl <= 0 || ttl >= remaining {
|
|
t.Fatal("restart reset/removed original TTL")
|
|
}
|
|
if revoked != "" {
|
|
call("GET", "/api/v1/users/me", revoked, nil, false, 401, nil)
|
|
revokedHash := sha256.Sum256([]byte(revoked))
|
|
if _, err = f.repo.GetSessionByTokenHash(ctx, revokedHash[:]); err == nil {
|
|
t.Fatal("revoked credential reappeared after restart")
|
|
}
|
|
}
|
|
})
|
|
}
|
|
}
|