ac98b5ddbd
AdminRequired gates admin endpoints by checking user IsAdmin flag. Placed AFTER AuthRequired; fetches user from repository, returns 403 for non-admins. Soft-deleted users are rejected with 401 since FindByID excludes them. Tests: admin passes, non-admin forbidden, soft-deleted admin rejected, missing user ID. Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent) Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
364 lines
9.3 KiB
Go
364 lines
9.3 KiB
Go
package middleware
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"gorm.io/driver/sqlite"
|
|
"gorm.io/gorm"
|
|
|
|
"github.com/dhao2001/mygo/internal/auth"
|
|
"github.com/dhao2001/mygo/internal/model"
|
|
"github.com/dhao2001/mygo/internal/repository"
|
|
)
|
|
|
|
func setupTestRouter(secret []byte) *gin.Engine {
|
|
gin.SetMode(gin.TestMode)
|
|
r := gin.New()
|
|
r.Use(AuthRequired(secret))
|
|
r.GET("/protected", func(c *gin.Context) {
|
|
c.JSON(http.StatusOK, gin.H{"user_id": MustGetUserID(c)})
|
|
})
|
|
return r
|
|
}
|
|
|
|
func TestAuthRequiredNoHeader(t *testing.T) {
|
|
r := setupTestRouter([]byte("test-secret"))
|
|
|
|
req := httptest.NewRequest(http.MethodGet, "/protected", nil)
|
|
rec := httptest.NewRecorder()
|
|
r.ServeHTTP(rec, req)
|
|
|
|
if rec.Code != http.StatusUnauthorized {
|
|
t.Errorf("status = %d, want %d", rec.Code, http.StatusUnauthorized)
|
|
}
|
|
}
|
|
|
|
func TestAuthRequiredInvalidFormat(t *testing.T) {
|
|
r := setupTestRouter([]byte("test-secret"))
|
|
|
|
req := httptest.NewRequest(http.MethodGet, "/protected", nil)
|
|
req.Header.Set("Authorization", "invalid")
|
|
rec := httptest.NewRecorder()
|
|
r.ServeHTTP(rec, req)
|
|
|
|
if rec.Code != http.StatusUnauthorized {
|
|
t.Errorf("status = %d, want %d", rec.Code, http.StatusUnauthorized)
|
|
}
|
|
}
|
|
|
|
func TestAuthRequiredNotBearer(t *testing.T) {
|
|
r := setupTestRouter([]byte("test-secret"))
|
|
|
|
req := httptest.NewRequest(http.MethodGet, "/protected", nil)
|
|
req.Header.Set("Authorization", "Basic dXNlcjpwYXNz")
|
|
rec := httptest.NewRecorder()
|
|
r.ServeHTTP(rec, req)
|
|
|
|
if rec.Code != http.StatusUnauthorized {
|
|
t.Errorf("status = %d, want %d", rec.Code, http.StatusUnauthorized)
|
|
}
|
|
}
|
|
|
|
func TestAuthRequiredExpiredToken(t *testing.T) {
|
|
secret := []byte("test-secret")
|
|
token, err := auth.GenerateAccessToken("user-1", secret, -1*time.Minute)
|
|
if err != nil {
|
|
t.Fatalf("GenerateAccessToken = %v", err)
|
|
}
|
|
|
|
r := setupTestRouter(secret)
|
|
req := httptest.NewRequest(http.MethodGet, "/protected", nil)
|
|
req.Header.Set("Authorization", "Bearer "+token)
|
|
rec := httptest.NewRecorder()
|
|
r.ServeHTTP(rec, req)
|
|
|
|
if rec.Code != http.StatusUnauthorized {
|
|
t.Errorf("status = %d, want %d", rec.Code, http.StatusUnauthorized)
|
|
}
|
|
}
|
|
|
|
func TestAuthRequiredValidToken(t *testing.T) {
|
|
secret := []byte("test-secret")
|
|
token, err := auth.GenerateAccessToken("user-1", secret, 15*time.Minute)
|
|
if err != nil {
|
|
t.Fatalf("GenerateAccessToken = %v", err)
|
|
}
|
|
|
|
r := setupTestRouter(secret)
|
|
req := httptest.NewRequest(http.MethodGet, "/protected", nil)
|
|
req.Header.Set("Authorization", "Bearer "+token)
|
|
rec := httptest.NewRecorder()
|
|
r.ServeHTTP(rec, req)
|
|
|
|
if rec.Code != http.StatusOK {
|
|
t.Errorf("status = %d, want %d", rec.Code, http.StatusOK)
|
|
}
|
|
}
|
|
|
|
func TestAuthRequiredRefreshTokenRejected(t *testing.T) {
|
|
secret := []byte("test-secret")
|
|
token, err := auth.GenerateRefreshToken("user-1", secret, 7*24*time.Hour)
|
|
if err != nil {
|
|
t.Fatalf("GenerateRefreshToken = %v", err)
|
|
}
|
|
|
|
r := setupTestRouter(secret)
|
|
req := httptest.NewRequest(http.MethodGet, "/protected", nil)
|
|
req.Header.Set("Authorization", "Bearer "+token)
|
|
rec := httptest.NewRecorder()
|
|
r.ServeHTTP(rec, req)
|
|
|
|
if rec.Code != http.StatusUnauthorized {
|
|
t.Errorf("status = %d, want %d (refresh token should be rejected)", rec.Code, http.StatusUnauthorized)
|
|
}
|
|
}
|
|
|
|
func TestGetUserID(t *testing.T) {
|
|
secret := []byte("test-secret")
|
|
token, err := auth.GenerateAccessToken("alice-42", secret, 15*time.Minute)
|
|
if err != nil {
|
|
t.Fatalf("GenerateAccessToken = %v", err)
|
|
}
|
|
|
|
r := setupTestRouter(secret)
|
|
req := httptest.NewRequest(http.MethodGet, "/protected", nil)
|
|
req.Header.Set("Authorization", "Bearer "+token)
|
|
rec := httptest.NewRecorder()
|
|
r.ServeHTTP(rec, req)
|
|
|
|
if rec.Code != http.StatusOK {
|
|
t.Fatalf("status = %d", rec.Code)
|
|
}
|
|
|
|
body := rec.Body.String()
|
|
if !strings.Contains(body, "alice-42") {
|
|
t.Errorf("response body %q does not contain user id", body)
|
|
}
|
|
}
|
|
|
|
func TestMustGetUserID(t *testing.T) {
|
|
secret := []byte("test-secret")
|
|
token, err := auth.GenerateAccessToken("bob-99", secret, 15*time.Minute)
|
|
if err != nil {
|
|
t.Fatalf("GenerateAccessToken = %v", err)
|
|
}
|
|
|
|
r := setupTestRouter(secret)
|
|
req := httptest.NewRequest(http.MethodGet, "/protected", nil)
|
|
req.Header.Set("Authorization", "Bearer "+token)
|
|
rec := httptest.NewRecorder()
|
|
r.ServeHTTP(rec, req)
|
|
|
|
if rec.Code != http.StatusOK {
|
|
t.Fatalf("status = %d", rec.Code)
|
|
}
|
|
|
|
body := rec.Body.String()
|
|
if !strings.Contains(body, "bob-99") {
|
|
t.Errorf("response body %q does not contain user id", body)
|
|
}
|
|
}
|
|
|
|
func TestMustGetUserIDPanics(t *testing.T) {
|
|
gin.SetMode(gin.TestMode)
|
|
r := gin.New()
|
|
r.GET("/naked", func(c *gin.Context) {
|
|
MustGetUserID(c) // should panic — no AuthRequired middleware applied
|
|
})
|
|
|
|
req := httptest.NewRequest(http.MethodGet, "/naked", nil)
|
|
rec := httptest.NewRecorder()
|
|
|
|
defer func() {
|
|
if r := recover(); r == nil {
|
|
t.Error("expected panic, got none")
|
|
}
|
|
}()
|
|
r.ServeHTTP(rec, req)
|
|
}
|
|
|
|
func TestAuthRequiredWrongSecret(t *testing.T) {
|
|
secret := []byte("test-secret")
|
|
token, err := auth.GenerateAccessToken("user-1", secret, 15*time.Minute)
|
|
if err != nil {
|
|
t.Fatalf("GenerateAccessToken = %v", err)
|
|
}
|
|
|
|
// Use a different secret for the middleware
|
|
r := setupTestRouter([]byte("different-secret"))
|
|
req := httptest.NewRequest(http.MethodGet, "/protected", nil)
|
|
req.Header.Set("Authorization", "Bearer "+token)
|
|
rec := httptest.NewRecorder()
|
|
r.ServeHTTP(rec, req)
|
|
|
|
if rec.Code != http.StatusUnauthorized {
|
|
t.Errorf("status = %d, want %d", rec.Code, http.StatusUnauthorized)
|
|
}
|
|
}
|
|
|
|
// --- AdminRequired tests ---
|
|
|
|
// errorBody extracts the error.message field from a JSON response body.
|
|
type errorBody struct {
|
|
Error struct {
|
|
Message string `json:"message"`
|
|
} `json:"error"`
|
|
}
|
|
|
|
func setupAdminTestDB(t *testing.T) repository.UserRepository {
|
|
t.Helper()
|
|
|
|
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
|
|
if err != nil {
|
|
t.Fatalf("open db: %v", err)
|
|
}
|
|
if err := db.AutoMigrate(&model.User{}); err != nil {
|
|
t.Fatalf("migrate: %v", err)
|
|
}
|
|
|
|
return repository.NewUserRepository(db)
|
|
}
|
|
|
|
// injectUserIDMiddleware simulates AuthRequired by injecting a user_id into the context.
|
|
func injectUserIDMiddleware(userID string) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
c.Set(userIDKey, userID)
|
|
c.Next()
|
|
}
|
|
}
|
|
|
|
func TestAdminRequired_AdminPasses(t *testing.T) {
|
|
repo := setupAdminTestDB(t)
|
|
ctx := context.Background()
|
|
|
|
user := &model.User{
|
|
ID: "admin-1",
|
|
Username: "admin",
|
|
Email: "admin@example.com",
|
|
IsAdmin: true,
|
|
Status: model.StatusActive,
|
|
}
|
|
if err := repo.Create(ctx, user); err != nil {
|
|
t.Fatalf("Create = %v", err)
|
|
}
|
|
|
|
gin.SetMode(gin.TestMode)
|
|
r := gin.New()
|
|
r.Use(injectUserIDMiddleware("admin-1"))
|
|
r.Use(AdminRequired(repo))
|
|
r.GET("/admin", func(c *gin.Context) {
|
|
c.JSON(http.StatusOK, gin.H{"status": "ok"})
|
|
})
|
|
|
|
req := httptest.NewRequest(http.MethodGet, "/admin", nil)
|
|
rec := httptest.NewRecorder()
|
|
r.ServeHTTP(rec, req)
|
|
|
|
if rec.Code != http.StatusOK {
|
|
t.Errorf("status = %d, want %d", rec.Code, http.StatusOK)
|
|
}
|
|
}
|
|
|
|
func TestAdminRequired_NonAdminForbidden(t *testing.T) {
|
|
repo := setupAdminTestDB(t)
|
|
ctx := context.Background()
|
|
|
|
user := &model.User{
|
|
ID: "user-1",
|
|
Username: "regular",
|
|
Email: "regular@example.com",
|
|
IsAdmin: false,
|
|
Status: model.StatusActive,
|
|
}
|
|
if err := repo.Create(ctx, user); err != nil {
|
|
t.Fatalf("Create = %v", err)
|
|
}
|
|
|
|
gin.SetMode(gin.TestMode)
|
|
r := gin.New()
|
|
r.Use(injectUserIDMiddleware("user-1"))
|
|
r.Use(AdminRequired(repo))
|
|
r.GET("/admin", func(c *gin.Context) {
|
|
c.JSON(http.StatusOK, gin.H{"status": "ok"})
|
|
})
|
|
|
|
req := httptest.NewRequest(http.MethodGet, "/admin", nil)
|
|
rec := httptest.NewRecorder()
|
|
r.ServeHTTP(rec, req)
|
|
|
|
if rec.Code != http.StatusForbidden {
|
|
t.Errorf("status = %d, want %d", rec.Code, http.StatusForbidden)
|
|
}
|
|
|
|
var body errorBody
|
|
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
|
|
t.Fatalf("unmarshal: %v", err)
|
|
}
|
|
if body.Error.Message != "admin access required" {
|
|
t.Errorf("message = %q, want %q", body.Error.Message, "admin access required")
|
|
}
|
|
}
|
|
|
|
func TestAdminRequired_SoftDeletedAdmin(t *testing.T) {
|
|
repo := setupAdminTestDB(t)
|
|
ctx := context.Background()
|
|
|
|
user := &model.User{
|
|
ID: "admin-2",
|
|
Username: "deleted_admin",
|
|
Email: "deleted_admin@example.com",
|
|
IsAdmin: true,
|
|
Status: model.StatusActive,
|
|
}
|
|
if err := repo.Create(ctx, user); err != nil {
|
|
t.Fatalf("Create = %v", err)
|
|
}
|
|
|
|
// Soft-delete the admin user
|
|
if err := repo.Delete(ctx, "admin-2"); err != nil {
|
|
t.Fatalf("Delete = %v", err)
|
|
}
|
|
|
|
gin.SetMode(gin.TestMode)
|
|
r := gin.New()
|
|
r.Use(injectUserIDMiddleware("admin-2"))
|
|
r.Use(AdminRequired(repo))
|
|
r.GET("/admin", func(c *gin.Context) {
|
|
c.JSON(http.StatusOK, gin.H{"status": "ok"})
|
|
})
|
|
|
|
req := httptest.NewRequest(http.MethodGet, "/admin", nil)
|
|
rec := httptest.NewRecorder()
|
|
r.ServeHTTP(rec, req)
|
|
|
|
if rec.Code != http.StatusUnauthorized {
|
|
t.Errorf("status = %d, want %d", rec.Code, http.StatusUnauthorized)
|
|
}
|
|
}
|
|
|
|
func TestAdminRequired_NoUserID(t *testing.T) {
|
|
repo := setupAdminTestDB(t)
|
|
|
|
gin.SetMode(gin.TestMode)
|
|
r := gin.New()
|
|
r.Use(AdminRequired(repo))
|
|
r.GET("/admin", func(c *gin.Context) {
|
|
c.JSON(http.StatusOK, gin.H{"status": "ok"})
|
|
})
|
|
|
|
req := httptest.NewRequest(http.MethodGet, "/admin", nil)
|
|
rec := httptest.NewRecorder()
|
|
r.ServeHTTP(rec, req)
|
|
|
|
if rec.Code != http.StatusUnauthorized {
|
|
t.Errorf("status = %d, want %d", rec.Code, http.StatusUnauthorized)
|
|
}
|
|
}
|