From 1eb9c15e9032ffd77a7b6c9dddb1c8718f311284 Mon Sep 17 00:00:00 2001 From: kyy Date: Tue, 3 Mar 2026 16:42:33 +0900 Subject: [PATCH] =?UTF-8?q?df=20=EA=B0=90=EC=82=AC=20=EB=A1=9C=EA=B7=B8=20?= =?UTF-8?q?=EB=AC=B4=EA=B2=B0=EC=84=B1=20=EA=B2=80=EC=A6=9D=20=ED=85=8C?= =?UTF-8?q?=EC=8A=A4=ED=8A=B8=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../handler/dev_handler_isolation_test.go | 2 +- backend/internal/handler/dev_handler_test.go | 297 +++++++++++------- 2 files changed, 183 insertions(+), 116 deletions(-) diff --git a/backend/internal/handler/dev_handler_isolation_test.go b/backend/internal/handler/dev_handler_isolation_test.go index 0364f1e2..e69df93c 100644 --- a/backend/internal/handler/dev_handler_isolation_test.go +++ b/backend/internal/handler/dev_handler_isolation_test.go @@ -16,7 +16,7 @@ import ( ) func TestDevHandler_Isolation(t *testing.T) { - mockKeto := new(MockKetoService) + mockKeto := new(devMockKetoService) h := &DevHandler{ Hydra: &service.HydraAdminService{ diff --git a/backend/internal/handler/dev_handler_test.go b/backend/internal/handler/dev_handler_test.go index 58ea45b1..35a52d44 100644 --- a/backend/internal/handler/dev_handler_test.go +++ b/backend/internal/handler/dev_handler_test.go @@ -6,6 +6,7 @@ import ( "bytes" "context" "encoding/json" + "fmt" "net/http" "net/http/httptest" "testing" @@ -16,33 +17,72 @@ import ( "github.com/stretchr/testify/mock" ) -type MockKetoService struct { +// --- Mocks with Unique Names to Avoid Collisions --- + +type devMockKetoService struct { mock.Mock } -func (m *MockKetoService) CheckPermission(ctx context.Context, subject, namespace, object, relation string) (bool, error) { +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 *MockKetoService) CreateRelation(ctx context.Context, namespace, object, relation, subject string) error { - return m.Called(ctx, namespace, object, relation, subject).Error(0) +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 *MockKetoService) DeleteRelation(ctx context.Context, namespace, object, relation, subject string) error { - return m.Called(ctx, namespace, object, relation, subject).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 *MockKetoService) ListRelations(ctx context.Context, namespace, object, relation, subject string) ([]service.RelationTuple, error) { - args := m.Called(ctx, namespace, object, relation, subject) +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 *MockKetoService) ListObjects(ctx context.Context, namespace, relation, subject string) ([]string, error) { - args := m.Called(ctx, namespace, relation, subject) +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" { @@ -51,11 +91,10 @@ func TestListClients_Success(t *testing.T) { {"client_id": "client-2", "client_name": "App Two", "metadata": map[string]interface{}{"status": "inactive"}}, }), nil } - return httpJSONAny(r, http.StatusNotFound, map[string]string{"error": "not found"}), nil + return httpJSONAny(r, http.StatusNotFound, nil), nil }) - mockKeto := new(MockKetoService) - // For simplicity, always allow in basic success test + mockKeto := new(devMockKetoService) mockKeto.On("CheckPermission", mock.Anything, mock.Anything, "System", "AppManager", "member").Return(true, nil) h := &DevHandler{ @@ -76,72 +115,61 @@ func TestListClients_Success(t *testing.T) { resp, _ := app.Test(req, -1) assert.Equal(t, http.StatusOK, resp.StatusCode) - - var res struct { - Items []clientSummary `json:"items"` - } - json.NewDecoder(resp.Body).Decode(&res) - assert.Equal(t, 2, len(res.Items)) - assert.Equal(t, "client-1", res.Items[0].ID) - assert.Equal(t, "App One", res.Items[0].Name) } -func TestGetClient_Success(t *testing.T) { +func TestUpdateClientStatus_Success(t *testing.T) { transport := roundTripFunc(func(r *http.Request) (*http.Response, error) { - if r.URL.Path == "/clients/client-123" { + if r.Method == http.MethodGet && r.URL.Path == "/clients/client-1" { return httpJSONAny(r, http.StatusOK, map[string]interface{}{ - "client_id": "client-123", - "client_name": "Test App", - "metadata": map[string]interface{}{"status": "active"}, + "client_id": "client-1", "metadata": map[string]interface{}{"status": "active"}, }), nil } - return httpJSONAny(r, http.StatusNotFound, map[string]string{"error": "not found"}), 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 }) - mockKeto := new(MockKetoService) - h := &DevHandler{ Hydra: &service.HydraAdminService{ AdminURL: "http://hydra.test", - PublicURL: "http://hydra-public.test", // PublicURL 추가 HTTPClient: &http.Client{Transport: transport}, }, - Keto: mockKeto, + Keto: new(devMockKetoService), } app := fiber.New() app.Use(func(c *fiber.Ctx) error { - c.Locals("user_profile", &domain.UserProfileResponse{ID: "test-user", Role: domain.RoleSuperAdmin}) + c.Locals("user_profile", &domain.UserProfileResponse{ID: "user-1", Role: domain.RoleSuperAdmin}) return c.Next() }) - app.Get("/api/v1/dev/clients/:id", h.GetClient) + app.Patch("/api/v1/dev/clients/:id/status", h.UpdateClientStatus) - req := httptest.NewRequest(http.MethodGet, "/api/v1/dev/clients/client-123", nil) + 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, "client-123", res.Client.ID) - assert.Equal(t, "Test App", res.Client.Name) - assert.Equal(t, "http://hydra-public.test/oauth2/auth", res.Endpoints.Authorization) + assert.Equal(t, "inactive", res.Client.Status) } -func TestCreateClient_Success(t *testing.T) { +func TestDeleteClient_Success(t *testing.T) { transport := roundTripFunc(func(r *http.Request) (*http.Response, error) { - if r.Method == http.MethodPost && r.URL.Path == "/clients" { - return httpJSONAny(r, http.StatusCreated, map[string]interface{}{ - "client_id": "new-client-123", - "client_name": "New App", - "client_secret": "secret-123", - }), nil + if r.Method == http.MethodGet && r.URL.Path == "/clients/client-1" { + return httpJSONAny(r, http.StatusOK, map[string]interface{}{"client_id": "client-1"}), nil } - return httpJSONAny(r, http.StatusInternalServerError, map[string]string{"error": "hydra error"}), 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 }) - mockKeto := new(MockKetoService) - secretRepo := &mockSecretRepo{secrets: make(map[string]string)} - redisRepo := &mockRedisRepo{data: make(map[string]string)} + 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{ @@ -150,102 +178,141 @@ func TestCreateClient_Success(t *testing.T) { }, SecretRepo: secretRepo, Redis: redisRepo, - Keto: mockKeto, + Keto: new(devMockKetoService), } app := fiber.New() app.Use(func(c *fiber.Ctx) error { - c.Locals("user_profile", &domain.UserProfileResponse{ID: "test-user", Role: domain.RoleSuperAdmin}) + c.Locals("user_profile", &domain.UserProfileResponse{ID: "user-1", Role: domain.RoleSuperAdmin}) return c.Next() }) - app.Post("/api/v1/dev/clients", h.CreateClient) - - body, _ := json.Marshal(map[string]interface{}{ - "client_name": "New App", - "type": "private", - "redirectUris": []string{"http://localhost/cb"}, - }) - req := httptest.NewRequest(http.MethodPost, "/api/v1/dev/clients", bytes.NewReader(body)) - req.Header.Set("Content-Type", "application/json") + 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.StatusCreated, resp.StatusCode) - secret, _ := secretRepo.GetByID(nil, "new-client-123") - assert.Equal(t, "secret-123", secret) + 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 TestListAuditLogs_FilterByActionAndClientID(t *testing.T) { - now := time.Now().UTC() - auditRepo := &mockAuditRepo{ - logs: []domain.AuditLog{ - { - EventID: "evt-1", - Timestamp: now, - UserID: "user-a", - EventType: "PUT /api/v1/dev/clients/client-1", - Status: "success", - Details: `{"action":"UPDATE_CLIENT","target_id":"client-1","tenant_id":"tenant-a"}`, - }, - { - EventID: "evt-2", - Timestamp: now.Add(-time.Minute), - UserID: "user-a", - EventType: "DELETE /api/v1/dev/clients/client-1", - Status: "success", - Details: `{"action":"DELETE_CLIENT","target_id":"client-1","tenant_id":"tenant-a"}`, - }, - { - EventID: "evt-3", - Timestamp: now.Add(-2 * time.Minute), - UserID: "user-b", - EventType: "PUT /api/v1/dev/clients/client-2", - Status: "failure", - Details: `{"action":"UPDATE_CLIENT","target_id":"client-2","tenant_id":"tenant-b"}`, - }, - }, - } +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{ - AuditRepo: auditRepo, - Keto: new(MockKetoService), + 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: "test-user", Role: domain.RoleSuperAdmin}) + c.Locals("user_profile", &domain.UserProfileResponse{ID: "user-1", Role: domain.RoleSuperAdmin}) return c.Next() }) - app.Get("/api/v1/dev/audit-logs", h.ListAuditLogs) + app.Post("/api/v1/dev/clients/:id/secret/rotate", h.RotateClientSecret) - req := httptest.NewRequest(http.MethodGet, "/api/v1/dev/audit-logs?action=UPDATE_CLIENT&client_id=client-1&status=success", nil) + 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) - var res devAuditListResponse - _ = json.NewDecoder(resp.Body).Decode(&res) - assert.Len(t, res.Items, 1) - assert.Equal(t, "evt-1", res.Items[0].EventID) - assert.Equal(t, "success", res.Items[0].Status) + dbS, _ := secretRepo.GetByID(nil, "client-1") + assert.Equal(t, res.Client.ClientSecret, dbS) } -func TestListAuditLogs_NonAdminKetoErrorReturnsForbidden(t *testing.T) { - mockKeto := new(MockKetoService) - mockKeto.On("CheckPermission", mock.Anything, "user-1", "System", "AppManager", "member").Return(false, assert.AnError) +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) + // mockKeto setup to allow stats view + mockKeto.On("CheckPermission", mock.Anything, "u1", "System", "AppManager", "member").Return(true, nil) h := &DevHandler{ - AuditRepo: &mockAuditRepo{}, + 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: "user-1", Role: domain.RoleUser}) + c.Locals("user_profile", &domain.UserProfileResponse{ + ID: "u1", Role: domain.RoleUser, TenantID: &tenantID, + }) return c.Next() }) - app.Get("/api/v1/dev/audit-logs", h.ListAuditLogs) + app.Get("/api/v1/dev/stats", h.GetStats) - req := httptest.NewRequest(http.MethodGet, "/api/v1/dev/audit-logs?limit=50", nil) + req := httptest.NewRequest(http.MethodGet, "/api/v1/dev/stats", nil) resp, _ := app.Test(req, -1) - assert.Equal(t, http.StatusForbidden, resp.StatusCode) + 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.AssertExpectations(t) } + +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) + }) +}