package handler import ( "baron-sso-backend/internal/domain" "baron-sso-backend/internal/service" "bytes" "context" "encoding/json" "fmt" "net/http" "net/http/httptest" "testing" "time" "github.com/gofiber/fiber/v2" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" ) // --- Mocks with Unique Names to Avoid Collisions --- type devMockKetoService struct { mock.Mock } func (m *devMockKetoService) CheckPermission(ctx context.Context, subject, namespace, object, relation string) (bool, error) { args := m.Called(ctx, subject, namespace, object, relation) return args.Bool(0), args.Error(1) } func (m *devMockKetoService) CreateRelation(ctx context.Context, ns, obj, rel, sub string) error { return m.Called(ctx, ns, obj, rel, sub).Error(0) } func (m *devMockKetoService) DeleteRelation(ctx context.Context, ns, obj, rel, sub string) error { return m.Called(ctx, ns, obj, rel, sub).Error(0) } func (m *devMockKetoService) ListRelations(ctx context.Context, ns, obj, rel, sub string) ([]service.RelationTuple, error) { args := m.Called(ctx, ns, obj, rel, sub) return args.Get(0).([]service.RelationTuple), args.Error(1) } func (m *devMockKetoService) ListObjects(ctx context.Context, ns, rel, sub string) ([]string, error) { args := m.Called(ctx, ns, rel, sub) return args.Get(0).([]string), args.Error(1) } type devMockRedisRepo struct { data map[string]string } func (m *devMockRedisRepo) Set(key, value string, exp time.Duration) error { if m.data == nil { m.data = make(map[string]string) } m.data[key] = value return nil } func (m *devMockRedisRepo) Get(key string) (string, error) { v, ok := m.data[key] if !ok { return "", fmt.Errorf("not found") } return v, nil } func (m *devMockRedisRepo) Delete(key string) error { delete(m.data, key) return nil } func (m *devMockRedisRepo) StoreVerificationCode(p, c string) error { return nil } func (m *devMockRedisRepo) GetVerificationCode(p string) (string, error) { return "", nil } func (m *devMockRedisRepo) DeleteVerificationCode(p string) error { return nil } type devEnhancedMockAuditRepo struct { mockAuditRepo countFailures int64 countSessions int64 } func (m *devEnhancedMockAuditRepo) CountFailuresSince(ctx context.Context, s time.Time, t string) (int64, error) { return m.countFailures, nil } func (m *devEnhancedMockAuditRepo) CountActiveSessionsSince(ctx context.Context, s time.Time, t string) (int64, error) { return m.countSessions, nil } // --- Tests --- func TestListClients_Success(t *testing.T) { transport := roundTripFunc(func(r *http.Request) (*http.Response, error) { if r.URL.Path == "/clients" { return httpJSONAny(r, http.StatusOK, []map[string]interface{}{ {"client_id": "client-1", "client_name": "App One", "metadata": map[string]interface{}{"status": "active"}}, {"client_id": "client-2", "client_name": "App Two", "metadata": map[string]interface{}{"status": "inactive"}}, }), nil } return httpJSONAny(r, http.StatusNotFound, nil), nil }) mockKeto := new(devMockKetoService) mockKeto.On("CheckPermission", mock.Anything, mock.Anything, "System", "AppManager", "member").Return(true, nil) h := &DevHandler{ Hydra: &service.HydraAdminService{ AdminURL: "http://hydra.test", HTTPClient: &http.Client{Transport: transport}, }, Keto: mockKeto, } app := fiber.New() app.Use(func(c *fiber.Ctx) error { c.Locals("user_profile", &domain.UserProfileResponse{ID: "test-user", Role: domain.RoleSuperAdmin}) return c.Next() }) app.Get("/api/v1/dev/clients", h.ListClients) req := httptest.NewRequest(http.MethodGet, "/api/v1/dev/clients", nil) resp, _ := app.Test(req, -1) assert.Equal(t, http.StatusOK, resp.StatusCode) } func TestUpdateClientStatus_Success(t *testing.T) { transport := roundTripFunc(func(r *http.Request) (*http.Response, error) { if r.Method == http.MethodGet && r.URL.Path == "/clients/client-1" { return httpJSONAny(r, http.StatusOK, map[string]interface{}{ "client_id": "client-1", "metadata": map[string]interface{}{"status": "active"}, }), nil } if r.Method == http.MethodPatch && r.URL.Path == "/clients/client-1" { return httpJSONAny(r, http.StatusOK, map[string]interface{}{ "client_id": "client-1", "metadata": map[string]interface{}{"status": "inactive"}, }), nil } return httpJSONAny(r, http.StatusNotFound, nil), nil }) h := &DevHandler{ Hydra: &service.HydraAdminService{ AdminURL: "http://hydra.test", HTTPClient: &http.Client{Transport: transport}, }, Keto: new(devMockKetoService), } app := fiber.New() app.Use(func(c *fiber.Ctx) error { c.Locals("user_profile", &domain.UserProfileResponse{ID: "user-1", Role: domain.RoleSuperAdmin}) return c.Next() }) app.Patch("/api/v1/dev/clients/:id/status", h.UpdateClientStatus) body, _ := json.Marshal(map[string]interface{}{"status": "inactive"}) req := httptest.NewRequest(http.MethodPatch, "/api/v1/dev/clients/client-1/status", bytes.NewReader(body)) req.Header.Set("Content-Type", "application/json") resp, _ := app.Test(req, -1) assert.Equal(t, http.StatusOK, resp.StatusCode) var res clientDetailResponse json.NewDecoder(resp.Body).Decode(&res) assert.Equal(t, "inactive", res.Client.Status) } func TestDeleteClient_Success(t *testing.T) { transport := roundTripFunc(func(r *http.Request) (*http.Response, error) { if r.Method == http.MethodGet && r.URL.Path == "/clients/client-1" { return httpJSONAny(r, http.StatusOK, map[string]interface{}{"client_id": "client-1"}), nil } if r.Method == http.MethodDelete && r.URL.Path == "/clients/client-1" { return &http.Response{StatusCode: http.StatusNoContent, Body: http.NoBody}, nil } return httpJSONAny(r, http.StatusNotFound, nil), nil }) secretRepo := &mockSecretRepo{secrets: map[string]string{"client-1": "secret"}} redisRepo := &devMockRedisRepo{data: map[string]string{"client_secret:client-1": "secret"}} h := &DevHandler{ Hydra: &service.HydraAdminService{ AdminURL: "http://hydra.test", HTTPClient: &http.Client{Transport: transport}, }, SecretRepo: secretRepo, Redis: redisRepo, Keto: new(devMockKetoService), } app := fiber.New() app.Use(func(c *fiber.Ctx) error { c.Locals("user_profile", &domain.UserProfileResponse{ID: "user-1", Role: domain.RoleSuperAdmin}) return c.Next() }) app.Delete("/api/v1/dev/clients/:id", h.DeleteClient) req := httptest.NewRequest(http.MethodDelete, "/api/v1/dev/clients/client-1", nil) resp, _ := app.Test(req, -1) assert.Equal(t, http.StatusNoContent, resp.StatusCode) s, _ := secretRepo.GetByID(nil, "client-1") assert.Empty(t, s) _, err := redisRepo.Get("client_secret:client-1") assert.Error(t, err) } func TestRotateClientSecret_Success(t *testing.T) { transport := roundTripFunc(func(r *http.Request) (*http.Response, error) { if r.Method == http.MethodGet && r.URL.Path == "/clients/client-1" { return httpJSONAny(r, http.StatusOK, map[string]interface{}{"client_id": "client-1"}), nil } if r.Method == http.MethodPut && r.URL.Path == "/clients/client-1" { var body map[string]interface{} json.NewDecoder(r.Body).Decode(&body) return httpJSONAny(r, http.StatusOK, body), nil } return httpJSONAny(r, http.StatusNotFound, nil), nil }) secretRepo := &mockSecretRepo{secrets: make(map[string]string)} redisRepo := &devMockRedisRepo{data: make(map[string]string)} h := &DevHandler{ Hydra: &service.HydraAdminService{ AdminURL: "http://hydra.test", HTTPClient: &http.Client{Transport: transport}, }, SecretRepo: secretRepo, Redis: redisRepo, Keto: new(devMockKetoService), } app := fiber.New() app.Use(func(c *fiber.Ctx) error { c.Locals("user_profile", &domain.UserProfileResponse{ID: "user-1", Role: domain.RoleSuperAdmin}) return c.Next() }) app.Post("/api/v1/dev/clients/:id/secret/rotate", h.RotateClientSecret) req := httptest.NewRequest(http.MethodPost, "/api/v1/dev/clients/client-1/secret/rotate", nil) resp, _ := app.Test(req, -1) assert.Equal(t, http.StatusOK, resp.StatusCode) var res clientDetailResponse json.NewDecoder(resp.Body).Decode(&res) assert.NotEmpty(t, res.Client.ClientSecret) dbS, _ := secretRepo.GetByID(nil, "client-1") assert.Equal(t, res.Client.ClientSecret, dbS) } func TestGetStats_Success(t *testing.T) { transport := roundTripFunc(func(r *http.Request) (*http.Response, error) { if r.URL.Path == "/clients" { return httpJSONAny(r, http.StatusOK, []map[string]interface{}{ {"client_id": "c1", "metadata": map[string]interface{}{"tenant_id": "t1"}}, {"client_id": "c2", "metadata": map[string]interface{}{"tenant_id": "t1"}}, {"client_id": "c3", "metadata": map[string]interface{}{"tenant_id": "t2"}}, }), nil } return httpJSONAny(r, http.StatusNotFound, nil), nil }) auditRepo := &devEnhancedMockAuditRepo{ countFailures: 7, countSessions: 3, } mockKeto := new(devMockKetoService) h := &DevHandler{ Hydra: &service.HydraAdminService{ AdminURL: "http://hydra.test", HTTPClient: &http.Client{Transport: transport}, }, AuditRepo: auditRepo, Keto: mockKeto, } app := fiber.New() tenantID := "t1" app.Use(func(c *fiber.Ctx) error { c.Locals("user_profile", &domain.UserProfileResponse{ ID: "u1", Role: domain.RoleTenantAdmin, TenantID: &tenantID, }) return c.Next() }) app.Get("/api/v1/dev/stats", h.GetStats) req := httptest.NewRequest(http.MethodGet, "/api/v1/dev/stats", nil) resp, _ := app.Test(req, -1) assert.Equal(t, http.StatusOK, resp.StatusCode) var res devStatsResponse json.NewDecoder(resp.Body).Decode(&res) assert.Equal(t, int64(2), res.TotalClients) assert.Equal(t, int64(7), res.AuthFailures) assert.Equal(t, int64(3), res.ActiveSessions) mockKeto.AssertNotCalled(t, "CheckPermission", mock.Anything, mock.Anything, "System", "AppManager", "member") } func TestDevHandler_NoAuditNoAction(t *testing.T) { h := &DevHandler{ Hydra: &service.HydraAdminService{AdminURL: "http://hydra.test"}, AuditRepo: nil, // Missing Keto: new(devMockKetoService), } t.Run("Mutating action fails when audit log is unavailable", func(t *testing.T) { app := fiber.New() app.Use(func(c *fiber.Ctx) error { if h.AuditRepo == nil { return c.Status(fiber.StatusServiceUnavailable).JSON(fiber.Map{"error": "Audit service unavailable"}) } return c.Next() }) app.Post("/api/v1/dev/clients", h.CreateClient) req := httptest.NewRequest(http.MethodPost, "/api/v1/dev/clients", bytes.NewReader([]byte("{}"))) resp, _ := app.Test(req, -1) assert.Equal(t, http.StatusServiceUnavailable, resp.StatusCode) }) } func TestListAuditLogs_TenantMemberForbidden(t *testing.T) { h := &DevHandler{ Hydra: &service.HydraAdminService{AdminURL: "http://hydra.test"}, AuditRepo: &mockAuditRepo{}, Keto: new(devMockKetoService), } app := fiber.New() tenantID := "tenant-a" app.Use(func(c *fiber.Ctx) error { c.Locals("user_profile", &domain.UserProfileResponse{ ID: "u-member", Role: domain.RoleUser, TenantID: &tenantID, }) return c.Next() }) app.Get("/api/v1/dev/audit-logs", h.ListAuditLogs) req := httptest.NewRequest(http.MethodGet, "/api/v1/dev/audit-logs", nil) resp, _ := app.Test(req, -1) assert.Equal(t, http.StatusForbidden, resp.StatusCode) } func TestListAuditLogs_RPAdminScope(t *testing.T) { auditRepo := &mockAuditRepo{ logs: []domain.AuditLog{ { EventID: "evt-1", EventType: "POST /api/v1/dev/clients", Status: "success", Timestamp: time.Now().UTC(), Details: `{"target_id":"client-allowed","tenant_id":"tenant-a","action":"CREATE_CLIENT"}`, }, { EventID: "evt-2", EventType: "POST /api/v1/dev/clients", Status: "success", Timestamp: time.Now().UTC().Add(-time.Minute), Details: `{"target_id":"client-other","tenant_id":"tenant-a","action":"CREATE_CLIENT"}`, }, }, } h := &DevHandler{ Hydra: &service.HydraAdminService{AdminURL: "http://hydra.test"}, AuditRepo: auditRepo, Keto: new(devMockKetoService), } app := fiber.New() tenantID := "tenant-a" app.Use(func(c *fiber.Ctx) error { c.Locals("user_profile", &domain.UserProfileResponse{ ID: "u-rp-admin", Role: domain.RoleRPAdmin, TenantID: &tenantID, Metadata: map[string]any{ "managed_client_ids": []any{"client-allowed"}, }, }) return c.Next() }) app.Get("/api/v1/dev/audit-logs", h.ListAuditLogs) req := httptest.NewRequest(http.MethodGet, "/api/v1/dev/audit-logs?limit=50", nil) resp, _ := app.Test(req, -1) assert.Equal(t, http.StatusOK, resp.StatusCode) var result devAuditListResponse _ = json.NewDecoder(resp.Body).Decode(&result) assert.Len(t, result.Items, 1) assert.Equal(t, "evt-1", result.Items[0].EventID) }