From 1eb9c15e9032ffd77a7b6c9dddb1c8718f311284 Mon Sep 17 00:00:00 2001 From: kyy Date: Tue, 3 Mar 2026 16:42:33 +0900 Subject: [PATCH 01/11] =?UTF-8?q?df=20=EA=B0=90=EC=82=AC=20=EB=A1=9C?= =?UTF-8?q?=EA=B7=B8=20=EB=AC=B4=EA=B2=B0=EC=84=B1=20=EA=B2=80=EC=A6=9D=20?= =?UTF-8?q?=ED=85=8C=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) + }) +} From 0ad57ab69c303f671b5b819f423ba85e6bea3f8e Mon Sep 17 00:00:00 2001 From: kyy Date: Tue, 3 Mar 2026 17:57:49 +0900 Subject: [PATCH 02/11] =?UTF-8?q?devfront=20e2e=20=ED=85=8C=EC=8A=A4?= =?UTF-8?q?=ED=8A=B8=20=EC=8B=9C=EB=82=98=EB=A6=AC=EC=98=A4=20=EB=B3=B4?= =?UTF-8?q?=EA=B0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- devfront/tests/devfront-audit.spec.ts | 108 ++++++ .../tests/devfront-clients-lifecycle.spec.ts | 121 ++++++ devfront/tests/devfront-consents.spec.ts | 45 +++ devfront/tests/devfront-security.spec.ts | 50 +++ devfront/tests/helpers/devfront-fixtures.ts | 362 ++++++++++++++++++ 5 files changed, 686 insertions(+) create mode 100644 devfront/tests/devfront-audit.spec.ts create mode 100644 devfront/tests/devfront-clients-lifecycle.spec.ts create mode 100644 devfront/tests/devfront-consents.spec.ts create mode 100644 devfront/tests/devfront-security.spec.ts create mode 100644 devfront/tests/helpers/devfront-fixtures.ts diff --git a/devfront/tests/devfront-audit.spec.ts b/devfront/tests/devfront-audit.spec.ts new file mode 100644 index 00000000..7f1cc18e --- /dev/null +++ b/devfront/tests/devfront-audit.spec.ts @@ -0,0 +1,108 @@ +import { expect, test } from "@playwright/test"; +import { + installDevApiMock, + makeClient, + seedAuth, + type AuditLog, + type Consent, +} from "./helpers/devfront-fixtures"; + +test.describe("DevFront audit logs", () => { + test.beforeEach(async ({ page }) => { + page.on("dialog", async (dialog) => { + await dialog.accept(); + }); + await seedAuth(page); + }); + + test("filtering and cursor pagination", async ({ page }) => { + const state = { + clients: [makeClient("client-audit", { name: "Audit app" })], + consents: [] as Consent[], + auditLogsByCursor: { + "": { + items: [ + { + event_id: "evt-1", + timestamp: "2026-03-03T09:00:00.000Z", + user_id: "actor-a", + event_type: "CLIENT_UPDATE", + status: "success", + ip_address: "127.0.0.1", + user_agent: "playwright", + details: JSON.stringify({ + action: "UPDATE_CLIENT", + target_id: "client-audit", + tenant_id: "tenant-a", + }), + }, + ], + next_cursor: "cursor-2", + }, + "cursor-2": { + items: [ + { + event_id: "evt-2", + timestamp: "2026-03-03T09:01:00.000Z", + user_id: "actor-b", + event_type: "CLIENT_ROTATE_SECRET", + status: "success", + ip_address: "127.0.0.1", + user_agent: "playwright", + details: JSON.stringify({ + action: "ROTATE_SECRET", + target_id: "client-audit", + tenant_id: "tenant-a", + }), + }, + ], + }, + }, + }; + await installDevApiMock(page, state); + + await page.goto("/audit-logs"); + await expect(page.getByText("UPDATE_CLIENT")).toBeVisible(); + + await page + .getByPlaceholder(/Client ID로 필터|Filter by Client ID/i) + .fill("client-audit"); + await page + .getByPlaceholder(/액션으로 필터|Filter by Action/i) + .fill("ROTATE_SECRET"); + + await page.getByRole("button", { name: /더 보기|Load more/i }).click(); + await expect(page.getByText("ROTATE_SECRET")).toBeVisible(); + }); + + test("realtime create/update actions should be visible", async ({ page }) => { + const state = { + clients: [makeClient("client-realtime", { name: "Realtime app" })], + consents: [] as Consent[], + auditLogs: [] as AuditLog[], + auditLogsByCursor: undefined, + }; + await installDevApiMock(page, state); + + await page.goto("/clients/new"); + await page.getByPlaceholder("My Awesome Application").fill("Realtime New App"); + await page + .getByPlaceholder(/https:\/\/app\.example\.com\/callback/i) + .fill("https://realtime.example.com/callback"); + await page.getByRole("button", { name: /앱 생성|Create/i }).click(); + await expect.poll(() => state.auditLogs.length).toBeGreaterThanOrEqual(1); + + await page.goto("/clients/client-realtime/settings"); + await page.getByPlaceholder("My Awesome Application").fill("Realtime Updated"); + await page.getByRole("button", { name: /^저장$|^Save$/i }).click(); + await expect.poll(() => state.auditLogs.length).toBeGreaterThanOrEqual(2); + + await page.goto("/audit-logs"); + await expect(page.getByText("CREATE_CLIENT")).toBeVisible({ + timeout: 30000, + }); + await expect(page.getByText("UPDATE_CLIENT")).toBeVisible({ + timeout: 30000, + }); + }); +}); diff --git a/devfront/tests/devfront-clients-lifecycle.spec.ts b/devfront/tests/devfront-clients-lifecycle.spec.ts new file mode 100644 index 00000000..d4a840be --- /dev/null +++ b/devfront/tests/devfront-clients-lifecycle.spec.ts @@ -0,0 +1,121 @@ +import { expect, test } from "@playwright/test"; +import { + installDevApiMock, + makeClient, + seedAuth, + type ClientStatus, + type Consent, +} from "./helpers/devfront-fixtures"; + +test.describe("DevFront clients lifecycle", () => { + test.beforeEach(async ({ page }) => { + page.on("dialog", async (dialog) => { + await dialog.accept(); + }); + await seedAuth(page); + }); + + test("create, update status, and delete", async ({ page }) => { + const state = { + clients: [makeClient("existing-client", { name: "Existing app" })], + consents: [] as Consent[], + updatedStatus: "active" as ClientStatus, + auditLogsByCursor: undefined, + onUpdateStatus(status: ClientStatus) { + this.updatedStatus = status; + }, + }; + await installDevApiMock(page, state); + + await page.goto("/clients"); + await expect(page.getByText("Existing app")).toBeVisible(); + + await page + .getByRole("button", { name: /연동 앱 추가|새 클라이언트|Create/i }) + .click(); + await expect(page).toHaveURL(/\/clients\/new$/); + + await page + .getByPlaceholder("My Awesome Application") + .fill("Playwright Created App"); + await page + .getByPlaceholder(/https:\/\/app\.example\.com\/callback/i) + .fill("https://playwright.example.com/callback"); + await page + .getByRole("button", { name: /앱 생성|클라이언트 생성|Create/i }) + .click(); + + await expect(page).toHaveURL(/\/clients\/client-2\/settings$/); + await expect( + page.getByRole("heading", { + name: /연동 앱 설정|클라이언트 설정|Client Settings/i, + }), + ).toBeVisible(); + + await page.getByRole("button", { name: /비활성|Inactive/i }).click(); + await page.getByRole("button", { name: /^저장$|^Save$/i }).click(); + await expect.poll(() => state.updatedStatus).toBe("inactive"); + + await page.getByRole("button", { name: /삭제|Delete/i }).click(); + await expect(page).toHaveURL(/\/clients$/); + await expect(page.getByText("Playwright Created App")).not.toBeVisible(); + }); + + test("rotate secret shows new value", async ({ page }) => { + let rotatedSecret = ""; + const state = { + clients: [makeClient("client-rotate", { name: "Rotate app" })], + consents: [] as Consent[], + auditLogsByCursor: undefined, + onRotateSecret(newSecret: string) { + rotatedSecret = newSecret; + }, + }; + await installDevApiMock(page, state); + + await page.goto("/clients/client-rotate"); + await expect( + page.getByRole("heading", { name: "Rotate app", exact: true }), + ).toBeVisible(); + + await page.getByTitle(/비밀키 재발급|Rotate/i).click(); + await expect.poll(() => rotatedSecret).toBe("client-rotate-rotated-secret"); + await expect(page.getByText("client-rotate-rotated-secret")).toBeVisible(); + }); + + test("update name and redirect URI should be persisted", async ({ page }) => { + const state = { + clients: [ + makeClient("client-edit", { + name: "Before Name", + redirectUris: ["https://before.example.com/callback"], + }), + ], + consents: [] as Consent[], + auditLogsByCursor: undefined, + }; + await installDevApiMock(page, state); + + await page.goto("/clients/client-edit/settings"); + await page.getByPlaceholder("My Awesome Application").fill("After Name"); + await page.getByRole("button", { name: /^저장$|^Save$/i }).click(); + await expect.poll(() => state.clients[0]?.name).toBe("After Name"); + + await page.goto("/clients/client-edit"); + await page + .getByRole("textbox", { name: /인증 콜백 URL|Callback/i }) + .fill("https://after.example.com/callback"); + await page + .getByRole("button", { name: /Redirect URIs 저장|Save/i }) + .click(); + + await expect.poll(() => state.clients[0]?.redirectUris[0]).toBe( + "https://after.example.com/callback", + ); + + await page.reload(); + await expect( + page.getByRole("textbox", { name: /인증 콜백 URL|Callback/i }), + ).toHaveValue(/https:\/\/after\.example\.com\/callback/); + }); +}); diff --git a/devfront/tests/devfront-consents.spec.ts b/devfront/tests/devfront-consents.spec.ts new file mode 100644 index 00000000..567419cb --- /dev/null +++ b/devfront/tests/devfront-consents.spec.ts @@ -0,0 +1,45 @@ +import { expect, test } from "@playwright/test"; +import { + installDevApiMock, + makeClient, + seedAuth, + type Consent, +} from "./helpers/devfront-fixtures"; + +test.describe("DevFront consents", () => { + test.beforeEach(async ({ page }) => { + page.on("dialog", async (dialog) => { + await dialog.accept(); + }); + await seedAuth(page); + }); + + test("consent list and revoke flow", async ({ page }) => { + const state = { + clients: [makeClient("client-consent", { name: "Consent app" })], + consents: [ + { + subject: "user-1", + userName: "Alice", + clientId: "client-consent", + clientName: "Consent app", + grantedScopes: ["openid", "profile"], + authenticatedAt: "2026-03-03T08:00:00.000Z", + createdAt: "2026-03-02T08:00:00.000Z", + status: "active", + tenantId: "tenant-a", + tenantName: "Tenant A", + }, + ] as Consent[], + auditLogsByCursor: undefined, + }; + await installDevApiMock(page, state); + + await page.goto("/clients/client-consent/consents"); + await expect(page.getByText("Alice")).toBeVisible(); + await expect(page.getByText("Tenant A")).toBeVisible(); + + await page.getByRole("button", { name: /권한 철회|Revoke/i }).click(); + await expect(page.getByText(/Revoked|철회/i).first()).toBeVisible(); + }); +}); diff --git a/devfront/tests/devfront-security.spec.ts b/devfront/tests/devfront-security.spec.ts new file mode 100644 index 00000000..75e684df --- /dev/null +++ b/devfront/tests/devfront-security.spec.ts @@ -0,0 +1,50 @@ +import { expect, test } from "@playwright/test"; +import { + installDevApiMock, + makeClient, + seedAuth, + type Consent, +} from "./helpers/devfront-fixtures"; + +test.describe("DevFront security and isolation", () => { + test.beforeEach(async ({ page }) => { + page.on("dialog", async (dialog) => { + await dialog.accept(); + }); + await seedAuth(page); + }); + + test("tenant isolation: forbidden client shows blocked error", async ({ + page, + }) => { + const state = { + clients: [makeClient("tenant-a-client", { name: "Tenant A app" })], + consents: [] as Consent[], + auditLogsByCursor: undefined, + }; + await installDevApiMock(page, state); + + await page.goto("/clients/tenant-b-client"); + await expect(page.getByText(/Error loading client|조회/i)).toBeVisible(); + }); + + test("RBAC: non-AppManager user should not see private apps", async ({ + page, + }) => { + const state = { + clients: [ + makeClient("pkce-client", { + name: "PKCE only app", + type: "pkce", + }), + ], + consents: [] as Consent[], + auditLogsByCursor: undefined, + }; + await installDevApiMock(page, state); + + await page.goto("/clients"); + await expect(page.getByText("PKCE only app")).toBeVisible(); + await expect(page.getByText("Server side App")).not.toBeVisible(); + }); +}); diff --git a/devfront/tests/helpers/devfront-fixtures.ts b/devfront/tests/helpers/devfront-fixtures.ts new file mode 100644 index 00000000..92b01ade --- /dev/null +++ b/devfront/tests/helpers/devfront-fixtures.ts @@ -0,0 +1,362 @@ +import type { Page, Route } from "@playwright/test"; + +export type ClientStatus = "active" | "inactive"; +export type ClientType = "private" | "pkce"; + +export type Client = { + id: string; + name: string; + type: ClientType; + status: ClientStatus; + redirectUris: string[]; + scopes: string[]; + createdAt: string; + clientSecret?: string; + metadata?: Record; +}; + +export type Consent = { + subject: string; + userName: string; + clientId: string; + clientName: string; + grantedScopes: string[]; + authenticatedAt?: string; + createdAt: string; + deletedAt?: string; + status: "active" | "revoked"; + tenantId: string; + tenantName: string; +}; + +export type AuditLog = { + event_id: string; + timestamp: string; + user_id: string; + event_type: string; + status: "success" | "failure"; + ip_address: string; + user_agent: string; + details: string; +}; + +export type DevApiMockState = { + clients: Client[]; + consents: Consent[]; + auditLogsByCursor?: Record; + auditLogs?: AuditLog[]; + onUpdateStatus?: (status: ClientStatus) => void; + onRotateSecret?: (newSecret: string) => void; +}; + +export function makeClient(id: string, overrides: Partial = {}): Client { + return { + id, + name: `${id} app`, + type: "private", + status: "active", + redirectUris: [`https://${id}.example.com/callback`], + scopes: ["openid", "profile", "email"], + createdAt: "2026-03-03T00:00:00.000Z", + clientSecret: `${id}-secret`, + metadata: {}, + ...overrides, + }; +} + +export async function seedAuth(page: Page) { + const nowInSeconds = Math.floor(Date.now() / 1000); + + await page.addInitScript((issuedAt) => { + const mockOidcUser = { + id_token: "playwright-id-token", + session_state: "playwright-session", + access_token: "playwright-access-token", + refresh_token: "playwright-refresh-token", + token_type: "Bearer", + scope: "openid profile email", + profile: { + sub: "playwright-user", + email: "playwright@example.com", + name: "Playwright User", + }, + expires_at: issuedAt + 3600, + }; + + window.localStorage.setItem( + "oidc.user:http://localhost:5000/oidc:devfront", + JSON.stringify(mockOidcUser), + ); + window.localStorage.setItem( + "oidc.user:http://localhost:5000/oidc/:devfront", + JSON.stringify(mockOidcUser), + ); + window.localStorage.setItem("dev_tenant_id", "tenant-a"); + }, nowInSeconds); +} + +function json(route: Route, payload: unknown, status = 200) { + return route.fulfill({ + status, + contentType: "application/json", + body: JSON.stringify(payload), + }); +} + +function parseClientId(pathname: string): string { + const parts = pathname.split("/").filter(Boolean); + return parts[parts.length - 1] ?? ""; +} + +export async function installDevApiMock(page: Page, state: DevApiMockState) { + const appendAuditLog = ( + eventType: string, + action: string, + targetId: string, + status: "success" | "failure" = "success", + ) => { + if (!state.auditLogs) return; + state.auditLogs.unshift({ + event_id: `evt-${Date.now()}-${Math.random().toString(16).slice(2, 8)}`, + timestamp: new Date().toISOString(), + user_id: "playwright-user", + event_type: eventType, + status, + ip_address: "127.0.0.1", + user_agent: "playwright", + details: JSON.stringify({ + action, + target_id: targetId, + tenant_id: "tenant-a", + }), + }); + }; + + await page.route("**/api/v1/dev/**", async (route) => { + const request = route.request(); + const url = new URL(request.url()); + const { pathname, searchParams } = url; + const method = request.method(); + + if (pathname === "/api/v1/dev/stats" && method === "GET") { + const total = state.clients.length; + return json(route, { + total_clients: total, + active_sessions: Math.max(1, total), + auth_failures_24h: 0, + }); + } + + if (pathname === "/api/v1/dev/clients" && method === "GET") { + return json(route, { + items: state.clients.map((client) => ({ + id: client.id, + name: client.name, + type: client.type, + status: client.status, + createdAt: client.createdAt, + redirectUris: client.redirectUris, + scopes: client.scopes, + })), + limit: 50, + offset: 0, + }); + } + + if (pathname === "/api/v1/dev/clients" && method === "POST") { + const payload = (request.postDataJSON() as { + name?: string; + type?: ClientType; + status?: ClientStatus; + redirectUris?: string[]; + scopes?: string[]; + metadata?: Record; + }) || { name: "created app" }; + + const created = makeClient(`client-${state.clients.length + 1}`, { + name: payload.name ?? "created app", + type: payload.type ?? "private", + status: payload.status ?? "active", + redirectUris: payload.redirectUris ?? [], + scopes: payload.scopes ?? ["openid"], + metadata: payload.metadata ?? {}, + }); + + state.clients.push(created); + appendAuditLog("CLIENT_CREATE", "CREATE_CLIENT", created.id); + return json(route, { + client: created, + endpoints: { + discovery: "https://issuer/.well-known/openid-configuration", + issuer: "https://issuer", + authorization: "https://issuer/oauth2/auth", + token: "https://issuer/oauth2/token", + userinfo: "https://issuer/userinfo", + }, + }); + } + + if ( + pathname.startsWith("/api/v1/dev/clients/") && + pathname.endsWith("/status") && + method === "PATCH" + ) { + const clientId = pathname.split("/")[5] ?? ""; + const payload = request.postDataJSON() as { status: ClientStatus }; + const found = state.clients.find((client) => client.id === clientId); + if (!found) return json(route, { error: "not found" }, 404); + found.status = payload.status; + appendAuditLog("CLIENT_UPDATE_STATUS", "UPDATE_CLIENT_STATUS", clientId); + state.onUpdateStatus?.(payload.status); + return json(route, { + client: found, + endpoints: { + discovery: "https://issuer/.well-known/openid-configuration", + issuer: "https://issuer", + authorization: "https://issuer/oauth2/auth", + token: "https://issuer/oauth2/token", + userinfo: "https://issuer/userinfo", + }, + }); + } + + if ( + pathname.startsWith("/api/v1/dev/clients/") && + pathname.endsWith("/secret/rotate") && + method === "POST" + ) { + const clientId = pathname.split("/")[5] ?? ""; + const found = state.clients.find((client) => client.id === clientId); + if (!found) return json(route, { error: "not found" }, 404); + found.clientSecret = `${clientId}-rotated-secret`; + appendAuditLog("CLIENT_ROTATE_SECRET", "ROTATE_SECRET", clientId); + state.onRotateSecret?.(found.clientSecret); + return json(route, { + client: found, + endpoints: { + discovery: "https://issuer/.well-known/openid-configuration", + issuer: "https://issuer", + authorization: "https://issuer/oauth2/auth", + token: "https://issuer/oauth2/token", + userinfo: "https://issuer/userinfo", + }, + }); + } + + if (pathname.startsWith("/api/v1/dev/clients/") && method === "PUT") { + const clientId = parseClientId(pathname); + const payload = (request.postDataJSON() as { + name?: string; + type?: ClientType; + scopes?: string[]; + redirectUris?: string[]; + metadata?: Record; + }) || { name: "updated app" }; + const found = state.clients.find((client) => client.id === clientId); + if (!found) return json(route, { error: "not found" }, 404); + if (payload.name) found.name = payload.name; + if (payload.type) found.type = payload.type; + if (payload.scopes) found.scopes = payload.scopes; + if (payload.redirectUris) found.redirectUris = payload.redirectUris; + if (payload.metadata) found.metadata = payload.metadata; + appendAuditLog("CLIENT_UPDATE", "UPDATE_CLIENT", clientId); + return json(route, { + client: found, + endpoints: { + discovery: "https://issuer/.well-known/openid-configuration", + issuer: "https://issuer", + authorization: "https://issuer/oauth2/auth", + token: "https://issuer/oauth2/token", + userinfo: "https://issuer/userinfo", + }, + }); + } + + if (pathname.startsWith("/api/v1/dev/clients/") && method === "DELETE") { + const clientId = parseClientId(pathname); + state.clients = state.clients.filter((client) => client.id !== clientId); + appendAuditLog("CLIENT_DELETE", "DELETE_CLIENT", clientId); + return route.fulfill({ status: 204 }); + } + + if (pathname.startsWith("/api/v1/dev/clients/") && method === "GET") { + const clientId = parseClientId(pathname); + const found = state.clients.find((client) => client.id === clientId); + if (!found) return json(route, { error: "forbidden" }, 403); + return json(route, { + client: found, + endpoints: { + discovery: "https://issuer/.well-known/openid-configuration", + issuer: "https://issuer", + authorization: "https://issuer/oauth2/auth", + token: "https://issuer/oauth2/token", + userinfo: "https://issuer/userinfo", + }, + }); + } + + if (pathname === "/api/v1/dev/consents" && method === "GET") { + const subject = searchParams.get("subject") || ""; + const clientId = searchParams.get("client_id") || ""; + const status = searchParams.get("status") || ""; + const items = state.consents.filter((row) => { + const matchesSubject = + !subject || row.subject.includes(subject) || row.userName.includes(subject); + const matchesClientId = !clientId || row.clientId === clientId; + const matchesStatus = !status || row.status === status; + return matchesSubject && matchesClientId && matchesStatus; + }); + return json(route, { items }); + } + + if (pathname === "/api/v1/dev/consents" && method === "DELETE") { + const subject = searchParams.get("subject") || ""; + const clientId = searchParams.get("client_id") || ""; + const target = state.consents.find( + (row) => row.subject === subject && row.clientId === clientId, + ); + if (target) { + target.status = "revoked"; + target.deletedAt = "2026-03-03T10:00:00.000Z"; + } + return route.fulfill({ status: 204 }); + } + + if (pathname === "/api/v1/dev/audit-logs" && method === "GET") { + if (state.auditLogsByCursor) { + const cursor = searchParams.get("cursor") || ""; + const pageSet = state.auditLogsByCursor[cursor] ?? { items: [] }; + return json(route, { + items: pageSet.items, + limit: 50, + cursor: cursor || undefined, + next_cursor: pageSet.next_cursor, + }); + } + + if (state.auditLogs) { + const action = searchParams.get("action") || ""; + const clientId = searchParams.get("client_id") || ""; + const status = searchParams.get("status") || ""; + const filtered = state.auditLogs.filter((item) => { + let parsedDetails: { action?: string; target_id?: string } = {}; + try { + parsedDetails = JSON.parse(item.details) as { + action?: string; + target_id?: string; + }; + } catch {} + const matchesAction = !action || parsedDetails.action === action; + const matchesClient = !clientId || parsedDetails.target_id === clientId; + const matchesStatus = !status || item.status === status; + return matchesAction && matchesClient && matchesStatus; + }); + return json(route, { items: filtered, limit: 50 }); + } + + return json(route, { items: [], limit: 50 }); + } + + return json(route, { error: `Unhandled ${method} ${pathname}` }, 404); + }); +} From dc9332809b709b0745e25274b2b4ffdb3345a868 Mon Sep 17 00:00:00 2001 From: kyy Date: Wed, 4 Mar 2026 09:44:12 +0900 Subject: [PATCH 03/11] =?UTF-8?q?Biome=20=EB=B0=8F=20Go=20=ED=8F=AC?= =?UTF-8?q?=EB=A7=B7=20=EC=A0=81=EC=9A=A9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../internal/handler/auth_handler_async_test.go | 1 + backend/internal/handler/dev_handler_test.go | 11 +++++++++-- devfront/tests/devfront-audit.spec.ts | 12 ++++++++---- .../tests/devfront-clients-lifecycle.spec.ts | 10 +++++----- devfront/tests/helpers/devfront-fixtures.ts | 17 +++++++++++++---- 5 files changed, 36 insertions(+), 15 deletions(-) diff --git a/backend/internal/handler/auth_handler_async_test.go b/backend/internal/handler/auth_handler_async_test.go index 00212e60..d206f48c 100644 --- a/backend/internal/handler/auth_handler_async_test.go +++ b/backend/internal/handler/auth_handler_async_test.go @@ -171,6 +171,7 @@ func (m *AsyncMockTenantService) ListTenants(ctx context.Context, limit, offset func (m *AsyncMockTenantService) ListManageableTenants(ctx context.Context, userID string) ([]domain.Tenant, error) { return nil, nil } + func (m *AsyncMockTenantService) IsDomainAllowed(ctx context.Context, domainName string) (bool, error) { return false, nil } diff --git a/backend/internal/handler/dev_handler_test.go b/backend/internal/handler/dev_handler_test.go index 35a52d44..19ede568 100644 --- a/backend/internal/handler/dev_handler_test.go +++ b/backend/internal/handler/dev_handler_test.go @@ -27,16 +27,20 @@ func (m *devMockKetoService) CheckPermission(ctx context.Context, subject, names 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) @@ -53,6 +57,7 @@ func (m *devMockRedisRepo) Set(key, value string, exp time.Duration) error { m.data[key] = value return nil } + func (m *devMockRedisRepo) Get(key string) (string, error) { v, ok := m.data[key] if !ok { @@ -60,13 +65,14 @@ func (m *devMockRedisRepo) Get(key string) (string, error) { } 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) 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 } +func (m *devMockRedisRepo) DeleteVerificationCode(p string) error { return nil } type devEnhancedMockAuditRepo struct { mockAuditRepo @@ -77,6 +83,7 @@ type devEnhancedMockAuditRepo struct { 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 } diff --git a/devfront/tests/devfront-audit.spec.ts b/devfront/tests/devfront-audit.spec.ts index 7f1cc18e..0d8774c9 100644 --- a/devfront/tests/devfront-audit.spec.ts +++ b/devfront/tests/devfront-audit.spec.ts @@ -1,10 +1,10 @@ import { expect, test } from "@playwright/test"; import { + type AuditLog, + type Consent, installDevApiMock, makeClient, seedAuth, - type AuditLog, - type Consent, } from "./helpers/devfront-fixtures"; test.describe("DevFront audit logs", () => { @@ -85,7 +85,9 @@ test.describe("DevFront audit logs", () => { await installDevApiMock(page, state); await page.goto("/clients/new"); - await page.getByPlaceholder("My Awesome Application").fill("Realtime New App"); + await page + .getByPlaceholder("My Awesome Application") + .fill("Realtime New App"); await page .getByPlaceholder(/https:\/\/app\.example\.com\/callback/i) .fill("https://realtime.example.com/callback"); @@ -93,7 +95,9 @@ test.describe("DevFront audit logs", () => { await expect.poll(() => state.auditLogs.length).toBeGreaterThanOrEqual(1); await page.goto("/clients/client-realtime/settings"); - await page.getByPlaceholder("My Awesome Application").fill("Realtime Updated"); + await page + .getByPlaceholder("My Awesome Application") + .fill("Realtime Updated"); await page.getByRole("button", { name: /^저장$|^Save$/i }).click(); await expect.poll(() => state.auditLogs.length).toBeGreaterThanOrEqual(2); diff --git a/devfront/tests/devfront-clients-lifecycle.spec.ts b/devfront/tests/devfront-clients-lifecycle.spec.ts index d4a840be..7a662395 100644 --- a/devfront/tests/devfront-clients-lifecycle.spec.ts +++ b/devfront/tests/devfront-clients-lifecycle.spec.ts @@ -1,10 +1,10 @@ import { expect, test } from "@playwright/test"; import { + type ClientStatus, + type Consent, installDevApiMock, makeClient, seedAuth, - type ClientStatus, - type Consent, } from "./helpers/devfront-fixtures"; test.describe("DevFront clients lifecycle", () => { @@ -109,9 +109,9 @@ test.describe("DevFront clients lifecycle", () => { .getByRole("button", { name: /Redirect URIs 저장|Save/i }) .click(); - await expect.poll(() => state.clients[0]?.redirectUris[0]).toBe( - "https://after.example.com/callback", - ); + await expect + .poll(() => state.clients[0]?.redirectUris[0]) + .toBe("https://after.example.com/callback"); await page.reload(); await expect( diff --git a/devfront/tests/helpers/devfront-fixtures.ts b/devfront/tests/helpers/devfront-fixtures.ts index 92b01ade..e2f092cc 100644 --- a/devfront/tests/helpers/devfront-fixtures.ts +++ b/devfront/tests/helpers/devfront-fixtures.ts @@ -43,13 +43,19 @@ export type AuditLog = { export type DevApiMockState = { clients: Client[]; consents: Consent[]; - auditLogsByCursor?: Record; + auditLogsByCursor?: Record< + string, + { items: AuditLog[]; next_cursor?: string } + >; auditLogs?: AuditLog[]; onUpdateStatus?: (status: ClientStatus) => void; onRotateSecret?: (newSecret: string) => void; }; -export function makeClient(id: string, overrides: Partial = {}): Client { +export function makeClient( + id: string, + overrides: Partial = {}, +): Client { return { id, name: `${id} app`, @@ -301,7 +307,9 @@ export async function installDevApiMock(page: Page, state: DevApiMockState) { const status = searchParams.get("status") || ""; const items = state.consents.filter((row) => { const matchesSubject = - !subject || row.subject.includes(subject) || row.userName.includes(subject); + !subject || + row.subject.includes(subject) || + row.userName.includes(subject); const matchesClientId = !clientId || row.clientId === clientId; const matchesStatus = !status || row.status === status; return matchesSubject && matchesClientId && matchesStatus; @@ -347,7 +355,8 @@ export async function installDevApiMock(page: Page, state: DevApiMockState) { }; } catch {} const matchesAction = !action || parsedDetails.action === action; - const matchesClient = !clientId || parsedDetails.target_id === clientId; + const matchesClient = + !clientId || parsedDetails.target_id === clientId; const matchesStatus = !status || item.status === status; return matchesAction && matchesClient && matchesStatus; }); From e2d3e389f3a1c18df08043a6ec1b6fdc8b897e75 Mon Sep 17 00:00:00 2001 From: kyy Date: Wed, 4 Mar 2026 13:09:41 +0900 Subject: [PATCH 04/11] =?UTF-8?q?=EC=97=AD=ED=95=A0=20=EC=A0=84=ED=99=98?= =?UTF-8?q?=20E2E=20=EB=B0=8F=20=EA=B6=8C=ED=95=9C=20=EC=95=88=EB=82=B4=20?= =?UTF-8?q?=EA=B2=80=EC=A6=9D=20=ED=85=8C=EC=8A=A4=ED=8A=B8=20=EC=B6=94?= =?UTF-8?q?=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- devfront/package.json | 1 + .../tests/devfront-role-switch-report.spec.ts | 141 ++++++++++++++++++ devfront/tests/devfront-security.spec.ts | 12 +- devfront/tests/helpers/devfront-fixtures.ts | 56 +++---- devfront/tests/helpers/evidence.ts | 24 +++ 5 files changed, 207 insertions(+), 27 deletions(-) create mode 100644 devfront/tests/devfront-role-switch-report.spec.ts create mode 100644 devfront/tests/helpers/evidence.ts diff --git a/devfront/package.json b/devfront/package.json index a8c53649..7db0ed87 100644 --- a/devfront/package.json +++ b/devfront/package.json @@ -9,6 +9,7 @@ "lint": "biome check .", "preview": "vite preview", "test": "playwright test", + "test:roles": "playwright test tests/devfront-role-switch-report.spec.ts", "test:ui": "playwright test --ui" }, "dependencies": { diff --git a/devfront/tests/devfront-role-switch-report.spec.ts b/devfront/tests/devfront-role-switch-report.spec.ts new file mode 100644 index 00000000..794564d7 --- /dev/null +++ b/devfront/tests/devfront-role-switch-report.spec.ts @@ -0,0 +1,141 @@ +import { expect, test } from "@playwright/test"; +import { + type AuditLog, + type Consent, + installDevApiMock, + makeClient, + seedAuth, +} from "./helpers/devfront-fixtures"; +import { captureEvidence } from "./helpers/evidence"; + +test.describe("DevFront role report", () => { + test.beforeEach(async ({ page }) => { + page.on("dialog", async (dialog) => { + await dialog.accept(); + }); + }); + + test("user(tenant_member) is blocked with 안내 문구", async ({ + page, + }, testInfo) => { + await seedAuth(page, "user"); + await installDevApiMock(page, { + clients: [], + consents: [] as Consent[], + auditLogs: [] as AuditLog[], + }); + + await page.goto("/clients"); + await expect( + page.getByText(/관리자 전용 화면|administrator only/i), + ).toBeVisible(); + await captureEvidence(page, testInfo, "role-user-blocked"); + }); + + test("rp_admin sees only assigned Gitea app and its logs", async ({ + page, + }, testInfo) => { + await seedAuth(page, "rp_admin"); + const state = { + clients: [makeClient("gitea-client", { name: "Gitea" })], + consents: [] as Consent[], + auditLogs: [ + { + event_id: "evt-rp-1", + timestamp: "2026-03-04T01:00:00.000Z", + user_id: "rp-admin-user", + event_type: "CLIENT_UPDATE", + status: "success" as const, + ip_address: "127.0.0.1", + user_agent: "playwright", + details: JSON.stringify({ + action: "UPDATE_CLIENT", + target_id: "gitea-client", + tenant_id: "tenant-a", + }), + }, + ] as AuditLog[], + }; + await installDevApiMock(page, state); + + await page.goto("/clients"); + await expect(page.getByRole("link", { name: /Gitea/ })).toBeVisible(); + await expect(page.getByText("gitea-client")).toBeVisible(); + await captureEvidence(page, testInfo, "role-rp-admin-clients"); + + await page.goto("/audit-logs"); + await expect(page.getByText("UPDATE_CLIENT")).toBeVisible(); + await expect(page.getByText("gitea-client")).toBeVisible(); + await captureEvidence(page, testInfo, "role-rp-admin-audit"); + }); + + test("tenant_admin can manage tenant apps and see tenant logs", async ({ + page, + }, testInfo) => { + await seedAuth(page, "tenant_admin"); + const state = { + clients: [ + makeClient("tenant-a-app-1", { name: "Tenant A CRM" }), + makeClient("tenant-a-app-2", { name: "Tenant A ERP" }), + ], + consents: [] as Consent[], + auditLogs: [] as AuditLog[], + auditLogsByCursor: undefined, + }; + await installDevApiMock(page, state); + + await page.goto("/clients"); + await expect(page.getByText("Tenant A CRM")).toBeVisible(); + await expect(page.getByText("Tenant A ERP")).toBeVisible(); + await captureEvidence(page, testInfo, "role-tenant-admin-clients"); + + await page.goto("/clients/tenant-a-app-1/settings"); + await page + .getByPlaceholder("My Awesome Application") + .fill("Tenant A CRM Updated"); + await page.getByRole("button", { name: /^저장$|^Save$/i }).click(); + + await page.goto("/audit-logs"); + await expect(page.getByText("UPDATE_CLIENT")).toBeVisible({ + timeout: 30000, + }); + await expect(page.getByText("tenant-a-app-1")).toBeVisible(); + await captureEvidence(page, testInfo, "role-tenant-admin-audit"); + }); + + test("super_admin sees all and can generate log entries", async ({ + page, + }, testInfo) => { + await seedAuth(page, "super_admin"); + const state = { + clients: [ + makeClient("tenant-a-app", { name: "Tenant A App" }), + makeClient("tenant-b-app", { name: "Tenant B App" }), + ], + consents: [] as Consent[], + auditLogs: [] as AuditLog[], + auditLogsByCursor: undefined, + }; + await installDevApiMock(page, state); + + await page.goto("/clients"); + await expect(page.getByText("Tenant A App")).toBeVisible(); + await expect(page.getByText("Tenant B App")).toBeVisible(); + await captureEvidence(page, testInfo, "role-super-admin-clients"); + + await page.goto("/clients/new"); + await page + .getByPlaceholder("My Awesome Application") + .fill("Super Admin Created App"); + await page + .getByPlaceholder(/https:\/\/app\.example\.com\/callback/i) + .fill("https://super-admin.example.com/callback"); + await page.getByRole("button", { name: /앱 생성|Create/i }).click(); + + await page.goto("/audit-logs"); + await expect(page.getByText("CREATE_CLIENT")).toBeVisible({ + timeout: 30000, + }); + await captureEvidence(page, testInfo, "role-super-admin-audit"); + }); +}); diff --git a/devfront/tests/devfront-security.spec.ts b/devfront/tests/devfront-security.spec.ts index 75e684df..f6c7cd1a 100644 --- a/devfront/tests/devfront-security.spec.ts +++ b/devfront/tests/devfront-security.spec.ts @@ -1,9 +1,9 @@ import { expect, test } from "@playwright/test"; import { + type Consent, installDevApiMock, makeClient, seedAuth, - type Consent, } from "./helpers/devfront-fixtures"; test.describe("DevFront security and isolation", () => { @@ -47,4 +47,14 @@ test.describe("DevFront security and isolation", () => { await expect(page.getByText("PKCE only app")).toBeVisible(); await expect(page.getByText("Server side App")).not.toBeVisible(); }); + + test("tenant_member user is blocked at AuthGuard", async ({ page }) => { + await seedAuth(page, "tenant_member"); + + await page.goto("/clients"); + await expect( + page.getByText(/DevFront는 관리자 전용 화면입니다|administrator access/i), + ).toBeVisible(); + await expect(page).toHaveURL(/\/clients$/); + }); }); diff --git a/devfront/tests/helpers/devfront-fixtures.ts b/devfront/tests/helpers/devfront-fixtures.ts index e2f092cc..fd154b43 100644 --- a/devfront/tests/helpers/devfront-fixtures.ts +++ b/devfront/tests/helpers/devfront-fixtures.ts @@ -70,35 +70,39 @@ export function makeClient( }; } -export async function seedAuth(page: Page) { +export async function seedAuth(page: Page, role?: string) { const nowInSeconds = Math.floor(Date.now() / 1000); - await page.addInitScript((issuedAt) => { - const mockOidcUser = { - id_token: "playwright-id-token", - session_state: "playwright-session", - access_token: "playwright-access-token", - refresh_token: "playwright-refresh-token", - token_type: "Bearer", - scope: "openid profile email", - profile: { - sub: "playwright-user", - email: "playwright@example.com", - name: "Playwright User", - }, - expires_at: issuedAt + 3600, - }; + await page.addInitScript( + ({ issuedAt, injectedRole }) => { + const mockOidcUser = { + id_token: "playwright-id-token", + session_state: "playwright-session", + access_token: "playwright-access-token", + refresh_token: "playwright-refresh-token", + token_type: "Bearer", + scope: "openid profile email", + profile: { + sub: "playwright-user", + email: "playwright@example.com", + name: "Playwright User", + ...(injectedRole ? { role: injectedRole } : {}), + }, + expires_at: issuedAt + 3600, + }; - window.localStorage.setItem( - "oidc.user:http://localhost:5000/oidc:devfront", - JSON.stringify(mockOidcUser), - ); - window.localStorage.setItem( - "oidc.user:http://localhost:5000/oidc/:devfront", - JSON.stringify(mockOidcUser), - ); - window.localStorage.setItem("dev_tenant_id", "tenant-a"); - }, nowInSeconds); + window.localStorage.setItem( + "oidc.user:http://localhost:5000/oidc:devfront", + JSON.stringify(mockOidcUser), + ); + window.localStorage.setItem( + "oidc.user:http://localhost:5000/oidc/:devfront", + JSON.stringify(mockOidcUser), + ); + window.localStorage.setItem("dev_tenant_id", "tenant-a"); + }, + { issuedAt: nowInSeconds, injectedRole: role ?? "" }, + ); } function json(route: Route, payload: unknown, status = 200) { diff --git a/devfront/tests/helpers/evidence.ts b/devfront/tests/helpers/evidence.ts new file mode 100644 index 00000000..a2507776 --- /dev/null +++ b/devfront/tests/helpers/evidence.ts @@ -0,0 +1,24 @@ +import type { Page, TestInfo } from "@playwright/test"; + +function safeName(name: string): string { + return name + .trim() + .toLowerCase() + .replace(/[^a-z0-9-_]+/g, "-") + .replace(/-+/g, "-") + .replace(/^-|-$/g, ""); +} + +export async function captureEvidence( + page: Page, + testInfo: TestInfo, + name: string, +) { + const filename = `${safeName(name)}.png`; + const fullPath = testInfo.outputPath(filename); + await page.screenshot({ path: fullPath, fullPage: true }); + await testInfo.attach(name, { + path: fullPath, + contentType: "image/png", + }); +} From 1b4b5d433f82b229743db2a7876f9734a4317772 Mon Sep 17 00:00:00 2001 From: kyy Date: Wed, 4 Mar 2026 13:13:54 +0900 Subject: [PATCH 05/11] =?UTF-8?q?=EC=97=AD=ED=95=A0=20=EB=9D=BC=EB=B2=A8?= =?UTF-8?q?=20=EB=B0=8F=20dev=20=EC=A0=91=EA=B7=BC=20=EC=95=88=EB=82=B4=20?= =?UTF-8?q?=EB=AC=B8=EA=B5=AC=20=ED=82=A4=20=EC=A0=95=EB=A6=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- adminfront/src/locales/en.toml | 5 +++++ adminfront/src/locales/ko.toml | 5 +++++ adminfront/src/locales/template.toml | 5 +++++ devfront/src/locales/en.toml | 5 +++++ devfront/src/locales/ko.toml | 5 +++++ devfront/src/locales/template.toml | 5 +++++ locales/en.toml | 5 +++++ locales/ko.toml | 5 +++++ locales/template.toml | 5 +++++ 9 files changed, 45 insertions(+) diff --git a/adminfront/src/locales/en.toml b/adminfront/src/locales/en.toml index 92c43ae3..2e86be36 100644 --- a/adminfront/src/locales/en.toml +++ b/adminfront/src/locales/en.toml @@ -741,6 +741,7 @@ view_audit_logs = "View Audit Logs" rp_admin = "RP ADMIN" super_admin = "SUPER ADMIN" tenant_admin = "TENANT ADMIN" +tenant_member = "TENANT MEMBER" user = "TENANT MEMBER" [ui.admin.tenants] @@ -966,6 +967,10 @@ system = "System" [ui.common.role] admin = "Admin" +rp_admin = "RP Admin" +super_admin = "Super Admin" +tenant_admin = "Tenant Admin" +tenant_member = "Tenant Member" user = "User" [ui.common.status] diff --git a/adminfront/src/locales/ko.toml b/adminfront/src/locales/ko.toml index 81bf79c1..aa6fd8ee 100644 --- a/adminfront/src/locales/ko.toml +++ b/adminfront/src/locales/ko.toml @@ -791,6 +791,7 @@ total_tenants = "전체 테넌트" rp_admin = "서비스 관리자 (RP Admin)" super_admin = "시스템 관리자 (Super Admin)" tenant_admin = "테넌트 관리자 (Tenant Admin)" +tenant_member = "일반 사용자 (Tenant Member)" user = "일반 사용자 (Tenant Member)" [ui.admin.tenants] @@ -1046,6 +1047,10 @@ system = "System" [ui.common.role] admin = "Admin" +rp_admin = "RP Admin" +super_admin = "Super Admin" +tenant_admin = "Tenant Admin" +tenant_member = "Tenant Member" user = "User" [ui.common.status] diff --git a/adminfront/src/locales/template.toml b/adminfront/src/locales/template.toml index d3f46c56..ae5d6a4b 100644 --- a/adminfront/src/locales/template.toml +++ b/adminfront/src/locales/template.toml @@ -714,6 +714,7 @@ rp_admin = "" super_admin = "" tenant_admin = "" tenant_member = "" +user = "" [ui.admin.tenants] add = "" @@ -922,6 +923,10 @@ system = "" [ui.common.role] admin = "" +rp_admin = "" +super_admin = "" +tenant_admin = "" +tenant_member = "" user = "" [ui.common.status] diff --git a/devfront/src/locales/en.toml b/devfront/src/locales/en.toml index 0abda2df..6936c8b2 100644 --- a/devfront/src/locales/en.toml +++ b/devfront/src/locales/en.toml @@ -207,6 +207,10 @@ unknown_error = "unknown error" [msg.dev] logout_confirm = "Are you sure you want to log out?" +[msg.dev.auth] +access_denied_description = "DevFront is for administrators only. Request access from your administrator." +access_denied_title = "Access denied." + [msg.dev.audit] empty = "No audit logs found." forbidden = "You do not have permission to view audit logs. Please request access from an administrator." @@ -890,6 +894,7 @@ tenant_dept = "TENANT / DEPT" [ui.common] add = "Add" back = "Back" +back_to_login = "Back to login" cancel = "Cancel" close = "Close" collapse = "Collapse" diff --git a/devfront/src/locales/ko.toml b/devfront/src/locales/ko.toml index 46e3d2e5..3879ffd8 100644 --- a/devfront/src/locales/ko.toml +++ b/devfront/src/locales/ko.toml @@ -207,6 +207,10 @@ unknown_error = "unknown error" [msg.dev] logout_confirm = "로그아웃 하시겠습니까?" +[msg.dev.auth] +access_denied_description = "DevFront는 관리자 전용 화면입니다. 권한이 필요하면 관리자에게 요청해 주세요." +access_denied_title = "접근 권한이 없습니다." + [msg.dev.audit] empty = "조회된 감사 로그가 없습니다." forbidden = "감사 로그를 조회할 권한이 없습니다. 관리자에게 권한을 요청해주세요." @@ -890,6 +894,7 @@ tenant_dept = "TENANT / DEPT" [ui.common] add = "추가" back = "돌아가기" +back_to_login = "로그인으로 돌아가기" cancel = "취소" close = "닫기" collapse = "접기" diff --git a/devfront/src/locales/template.toml b/devfront/src/locales/template.toml index b2603ada..d3fa256f 100644 --- a/devfront/src/locales/template.toml +++ b/devfront/src/locales/template.toml @@ -207,6 +207,10 @@ unknown_error = "" [msg.dev] logout_confirm = "" +[msg.dev.auth] +access_denied_description = "" +access_denied_title = "" + [msg.dev.audit] empty = "" forbidden = "" @@ -902,6 +906,7 @@ tenant_dept = "" [ui.common] add = "" back = "" +back_to_login = "" cancel = "" close = "" collapse = "" diff --git a/locales/en.toml b/locales/en.toml index af2e11bd..aebc6602 100644 --- a/locales/en.toml +++ b/locales/en.toml @@ -273,6 +273,10 @@ unknown_error = "unknown error" [msg.dev] logout_confirm = "Are you sure you want to log out?" +[msg.dev.auth] +access_denied_description = "DevFront is for administrators only. Request access from your administrator." +access_denied_title = "Access denied." + [msg.dev.audit] empty = "No audit logs found." forbidden = "You do not have permission to view audit logs. Please request access from an administrator." @@ -1056,6 +1060,7 @@ add = "Add" admin_only = "Admin Only" assign = "Assign" back = "Back" +back_to_login = "Back to login" cancel = "Cancel" close = "Close" collapse = "Collapse" diff --git a/locales/ko.toml b/locales/ko.toml index abc0bfff..b97c29a6 100644 --- a/locales/ko.toml +++ b/locales/ko.toml @@ -273,6 +273,10 @@ unknown_error = "unknown error" [msg.dev] logout_confirm = "로그아웃 하시겠습니까?" +[msg.dev.auth] +access_denied_description = "DevFront는 관리자 전용 화면입니다. 권한이 필요하면 관리자에게 요청해 주세요." +access_denied_title = "접근 권한이 없습니다." + [msg.dev.audit] empty = "조회된 감사 로그가 없습니다." forbidden = "감사 로그를 조회할 권한이 없습니다. 관리자에게 권한을 요청해주세요." @@ -1056,6 +1060,7 @@ add = "추가" admin_only = "관리자 전용" assign = "할당" back = "돌아가기" +back_to_login = "로그인으로 돌아가기" cancel = "취소" close = "닫기" collapse = "접기" diff --git a/locales/template.toml b/locales/template.toml index 37627a41..77613d27 100644 --- a/locales/template.toml +++ b/locales/template.toml @@ -213,6 +213,10 @@ unknown_error = "" [msg.dev] logout_confirm = "" +[msg.dev.auth] +access_denied_description = "" +access_denied_title = "" + [msg.dev.audit] empty = "" forbidden = "" @@ -921,6 +925,7 @@ add = "" admin_only = "" assign = "" back = "" +back_to_login = "" cancel = "" close = "" collapse = "" From 0f8b19a9b1c3ee6c31436a67982ab33397b7ec71 Mon Sep 17 00:00:00 2001 From: kyy Date: Wed, 4 Mar 2026 13:15:28 +0900 Subject: [PATCH 06/11] =?UTF-8?q?=EA=B4=80=EB=A6=AC=EC=9E=90=20=EA=B6=8C?= =?UTF-8?q?=ED=95=9C=20=ED=8C=90=EB=B3=84=20=EB=A1=9C=EC=A7=81=20=EB=B3=B4?= =?UTF-8?q?=EC=99=84=EC=9C=BC=EB=A1=9C=20=EB=A9=94=EB=89=B4/=EC=A0=91?= =?UTF-8?q?=EA=B7=BC=20=EC=A0=9C=EC=96=B4=20=EC=9D=BC=EC=B9=98=ED=99=94?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- devfront/src/components/layout/AppLayout.tsx | 44 ++++++++++++-------- devfront/src/features/auth/AuthGuard.tsx | 36 ++++++++++++++++ devfront/src/lib/role.ts | 25 +++++++++++ 3 files changed, 88 insertions(+), 17 deletions(-) create mode 100644 devfront/src/lib/role.ts diff --git a/devfront/src/components/layout/AppLayout.tsx b/devfront/src/components/layout/AppLayout.tsx index 66b8d175..92b458a8 100644 --- a/devfront/src/components/layout/AppLayout.tsx +++ b/devfront/src/components/layout/AppLayout.tsx @@ -10,6 +10,7 @@ import { useEffect, useRef, useState } from "react"; import { useAuth } from "react-oidc-context"; import { NavLink, Outlet, useNavigate } from "react-router-dom"; import { t } from "../../lib/i18n"; +import { resolveProfileRole } from "../../lib/role"; import LanguageSelector from "../common/LanguageSelector"; import { Toaster } from "../ui/toaster"; @@ -96,6 +97,14 @@ function AppLayout() { auth.user?.profile?.email?.toString().trim() || t("ui.dev.profile.unknown_email", "unknown@example.com"); const profileInitial = profileName.charAt(0).toUpperCase(); + const currentRole = resolveProfileRole( + auth.user?.profile as Record | undefined, + ); + const isDevConsoleAllowed = [ + "super_admin", + "tenant_admin", + "rp_admin", + ].includes(currentRole); const expiresAtSec = auth.user?.expires_at; const remainingMs = typeof expiresAtSec === "number" ? expiresAtSec * 1000 - nowMs : null; @@ -191,23 +200,24 @@ function AppLayout() {
- {navItems.map(({ labelKey, labelFallback, to, icon: Icon }) => ( - - [ - "flex items-center gap-3 rounded-xl px-3 py-3 text-sm transition", - isActive - ? "bg-primary/10 text-primary shadow-[0_12px_40px_rgba(54,211,153,0.18)]" - : "text-muted-foreground hover:bg-muted/10 hover:text-foreground", - ].join(" ") - } - > - - {t(labelKey, labelFallback)} - - ))} + {isDevConsoleAllowed && + navItems.map(({ labelKey, labelFallback, to, icon: Icon }) => ( + + [ + "flex items-center gap-3 rounded-xl px-3 py-3 text-sm transition", + isActive + ? "bg-primary/10 text-primary shadow-[0_12px_40px_rgba(54,211,153,0.18)]" + : "text-muted-foreground hover:bg-muted/10 hover:text-foreground", + ].join(" ") + } + > + + {t(labelKey, labelFallback)} + + ))}
diff --git a/devfront/src/features/auth/AuthGuard.tsx b/devfront/src/features/auth/AuthGuard.tsx index 26069583..0ab7c9fd 100644 --- a/devfront/src/features/auth/AuthGuard.tsx +++ b/devfront/src/features/auth/AuthGuard.tsx @@ -1,5 +1,7 @@ import { useAuth } from "react-oidc-context"; import { Navigate, Outlet } from "react-router-dom"; +import { t } from "../../lib/i18n"; +import { resolveProfileRole } from "../../lib/role"; export default function AuthGuard() { const auth = useAuth(); @@ -16,5 +18,39 @@ export default function AuthGuard() { return ; } + const normalizedRole = resolveProfileRole( + auth.user?.profile as Record | undefined, + ); + const isTenantMember = + normalizedRole === "user" || normalizedRole === "tenant_member"; + + if (isTenantMember) { + return ( +
+
+

+ {t("msg.dev.auth.access_denied_title", "접근 권한이 없습니다.")} +

+

+ {t( + "msg.dev.auth.access_denied_description", + "DevFront는 관리자 전용 화면입니다. 권한이 필요하면 관리자에게 요청해 주세요.", + )} +

+ +
+
+ ); + } + return ; } diff --git a/devfront/src/lib/role.ts b/devfront/src/lib/role.ts new file mode 100644 index 00000000..f4400c72 --- /dev/null +++ b/devfront/src/lib/role.ts @@ -0,0 +1,25 @@ +export function normalizeRole(rawRole: unknown): string { + if (typeof rawRole !== "string") return ""; + const role = rawRole.trim().toLowerCase(); + if (role === "tenant_member") return "user"; + if (role === "admin") return "tenant_admin"; + if (role === "superadmin") return "super_admin"; + if (role === "tenantadmin") return "tenant_admin"; + if (role === "rpadmin") return "rp_admin"; + return role; +} + +export function resolveProfileRole(profile: Record | undefined) { + if (!profile) return ""; + const candidates = [ + profile.role, + profile.grade, + profile["custom:role"], + profile["custom:grade"], + ]; + for (const candidate of candidates) { + const normalized = normalizeRole(candidate); + if (normalized) return normalized; + } + return ""; +} From eac16cfcd965adcbcf9c3716fc55a7667bf26b95 Mon Sep 17 00:00:00 2001 From: kyy Date: Wed, 4 Mar 2026 13:16:34 +0900 Subject: [PATCH 07/11] =?UTF-8?q?4=EB=8B=A8=EA=B3=84=20=EC=97=AD=ED=95=A0?= =?UTF-8?q?=20=EC=A0=95=EA=B7=9C=ED=99=94=20=EB=B0=8F=20dev=20=EA=B6=8C?= =?UTF-8?q?=ED=95=9C=20=EC=8A=A4=EC=BD=94=ED=94=84=20=EA=B2=80=EC=A6=9D=20?= =?UTF-8?q?=EA=B0=95=ED=99=94?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/internal/bootstrap/keto_sync.go | 5 +- backend/internal/domain/user.go | 15 + backend/internal/domain/user_test.go | 29 ++ backend/internal/handler/auth_handler.go | 18 +- backend/internal/handler/dev_handler.go | 434 ++++++++++++------ .../handler/dev_handler_isolation_test.go | 54 ++- backend/internal/handler/dev_handler_test.go | 81 +++- .../internal/handler/relying_party_handler.go | 7 +- backend/internal/handler/tenant_handler.go | 2 +- backend/internal/handler/user_handler.go | 33 +- backend/internal/middleware/rbac.go | 20 +- 11 files changed, 521 insertions(+), 177 deletions(-) create mode 100644 backend/internal/domain/user_test.go diff --git a/backend/internal/bootstrap/keto_sync.go b/backend/internal/bootstrap/keto_sync.go index b185b39a..7d7f12fc 100644 --- a/backend/internal/bootstrap/keto_sync.go +++ b/backend/internal/bootstrap/keto_sync.go @@ -34,15 +34,16 @@ func SyncKetoRelations(db *gorm.DB, keto service.KetoService) error { } slog.Info("Syncing users to Keto", "count", len(users)) for _, u := range users { + role := domain.NormalizeRole(u.Role) // Membership if u.TenantID != nil { _ = keto.CreateRelation(ctx, "Tenant", *u.TenantID, "members", "User:"+u.ID) } // Roles - if u.Role == domain.RoleSuperAdmin { + if role == domain.RoleSuperAdmin { _ = keto.CreateRelation(ctx, "System", "global", "super_admins", "User:"+u.ID) - } else if u.Role == domain.RoleTenantAdmin && u.TenantID != nil { + } else if role == domain.RoleTenantAdmin && u.TenantID != nil { _ = keto.CreateRelation(ctx, "Tenant", *u.TenantID, "admins", "User:"+u.ID) } } diff --git a/backend/internal/domain/user.go b/backend/internal/domain/user.go index 6a27ed2d..448f116e 100644 --- a/backend/internal/domain/user.go +++ b/backend/internal/domain/user.go @@ -1,6 +1,7 @@ package domain import ( + "strings" "time" "github.com/google/uuid" @@ -15,6 +16,20 @@ const ( RoleUser = "user" // 일반 사용자 ) +// NormalizeRole maps legacy/synonym role values to canonical role keys. +func NormalizeRole(role string) string { + normalized := strings.ToLower(strings.TrimSpace(role)) + switch normalized { + case "tenant_member": + return RoleUser + case "admin": + // Legacy admin is treated as tenant admin for least-privilege compatibility. + return RoleTenantAdmin + default: + return normalized + } +} + // User represents the user model stored in PostgreSQL type User struct { ID string `gorm:"primaryKey;type:uuid;default:gen_random_uuid()" json:"id"` diff --git a/backend/internal/domain/user_test.go b/backend/internal/domain/user_test.go new file mode 100644 index 00000000..737ac0ad --- /dev/null +++ b/backend/internal/domain/user_test.go @@ -0,0 +1,29 @@ +package domain + +import "testing" + +func TestNormalizeRole(t *testing.T) { + tests := []struct { + name string + in string + want string + }{ + {name: "super admin unchanged", in: "super_admin", want: RoleSuperAdmin}, + {name: "tenant admin unchanged", in: "tenant_admin", want: RoleTenantAdmin}, + {name: "rp admin unchanged", in: "rp_admin", want: RoleRPAdmin}, + {name: "user unchanged", in: "user", want: RoleUser}, + {name: "legacy admin", in: "admin", want: RoleTenantAdmin}, + {name: "legacy tenant member", in: "tenant_member", want: RoleUser}, + {name: "trim and lower", in: " ADMIN ", want: RoleTenantAdmin}, + {name: "unknown role pass-through", in: "custom_role", want: "custom_role"}, + {name: "empty", in: " ", want: ""}, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + if got := NormalizeRole(tc.in); got != tc.want { + t.Fatalf("NormalizeRole(%q)=%q, want %q", tc.in, got, tc.want) + } + }) + } +} diff --git a/backend/internal/handler/auth_handler.go b/backend/internal/handler/auth_handler.go index d0d63baa..04d7a849 100644 --- a/backend/internal/handler/auth_handler.go +++ b/backend/internal/handler/auth_handler.go @@ -4004,17 +4004,19 @@ func (h *AuthHandler) resolveCurrentProfile(c *fiber.Ctx) (*domain.UserProfileRe // 2. Role Override for real profile or fallback to Mock Profile if profile != nil { if isDev && mockRole != "" { + normalizedMockRole := domain.NormalizeRole(mockRole) slog.Info("🔑 [AUTH] Overriding real profile role", - "email", profile.Email, "originalRole", profile.Role, "overriddenRole", mockRole) - profile.Role = mockRole + "email", profile.Email, "originalRole", profile.Role, "overriddenRole", normalizedMockRole) + profile.Role = normalizedMockRole } } else if isDev && mockRole != "" && token == "" && cookie == "" { + normalizedMockRole := domain.NormalizeRole(mockRole) slog.Info("🔑 [AUTH] Using full Mock Auth (no session)", "role", mockRole) profile = &domain.UserProfileResponse{ ID: "00000000-0000-0000-0000-000000000000", Email: "mock@hmac.kr", Name: "Dev Mock User", - Role: mockRole, + Role: normalizedMockRole, } if tid := c.Get("X-Tenant-ID"); tid != "" { profile.TenantID = &tid @@ -4027,6 +4029,7 @@ func (h *AuthHandler) resolveCurrentProfile(c *fiber.Ctx) (*domain.UserProfileRe } // 3. Post-Process (Defaults & Metadata Enrichment) + profile.Role = domain.NormalizeRole(profile.Role) if profile.Role == "" { profile.Role = domain.RoleUser } @@ -5115,6 +5118,7 @@ func (h *AuthHandler) mapKratosIdentityToProfile(identityID string, traits map[s compCode, _ := traits["companyCode"].(string) role, _ := traits["role"].(string) tenantID, _ := traits["tenant_id"].(string) + relyingPartyID, _ := traits["relying_party_id"].(string) profile := &domain.UserProfileResponse{ ID: identityID, @@ -5124,18 +5128,22 @@ func (h *AuthHandler) mapKratosIdentityToProfile(identityID string, traits map[s Department: dept, AffiliationType: affType, CompanyCode: compCode, - Role: role, + Role: domain.NormalizeRole(role), Metadata: make(map[string]any), } if tenantID != "" { profile.TenantID = &tenantID } + if strings.TrimSpace(relyingPartyID) != "" { + rpID := strings.TrimSpace(relyingPartyID) + profile.RelyingPartyID = &rpID + } coreTraits := map[string]bool{ "email": true, "name": true, "phone_number": true, "grade": true, "companyCode": true, "department": true, - "affiliationType": true, "role": true, "tenant_id": true, + "affiliationType": true, "role": true, "tenant_id": true, "relying_party_id": true, } for k, v := range traits { if !coreTraits[k] { diff --git a/backend/internal/handler/dev_handler.go b/backend/internal/handler/dev_handler.go index 91f80b10..a15c1ba4 100644 --- a/backend/internal/handler/dev_handler.go +++ b/backend/internal/handler/dev_handler.go @@ -140,6 +140,127 @@ type clientUpsertRequest struct { Metadata *map[string]interface{} `json:"metadata"` } +func normalizeUserRole(role string) string { + return domain.NormalizeRole(role) +} + +func isDevConsoleRoleAllowed(role string) bool { + switch normalizeUserRole(role) { + case domain.RoleSuperAdmin, domain.RoleTenantAdmin, domain.RoleRPAdmin: + return true + default: + return false + } +} + +func (h *DevHandler) getCurrentProfile(c *fiber.Ctx) *domain.UserProfileResponse { + if profile, ok := c.Locals("user_profile").(*domain.UserProfileResponse); ok && profile != nil { + return profile + } + if h.Auth != nil { + enriched, err := h.Auth.GetEnrichedProfile(c) + if err == nil && enriched != nil { + c.Locals("user_profile", enriched) + return enriched + } + } + return nil +} + +func tenantIDFromProfile(profile *domain.UserProfileResponse) string { + if profile == nil || profile.TenantID == nil { + return "" + } + return strings.TrimSpace(*profile.TenantID) +} + +func addClientIDToSet(set map[string]struct{}, raw any) { + switch value := raw.(type) { + case string: + for _, chunk := range strings.Split(value, ",") { + id := strings.TrimSpace(chunk) + if id != "" { + set[id] = struct{}{} + } + } + case []string: + for _, item := range value { + id := strings.TrimSpace(item) + if id != "" { + set[id] = struct{}{} + } + } + case []any: + for _, item := range value { + if str, ok := item.(string); ok { + id := strings.TrimSpace(str) + if id != "" { + set[id] = struct{}{} + } + } + } + } +} + +func managedClientIDsFromProfile(profile *domain.UserProfileResponse) map[string]struct{} { + ids := make(map[string]struct{}) + if profile == nil { + return ids + } + + if profile.RelyingPartyID != nil { + if id := strings.TrimSpace(*profile.RelyingPartyID); id != "" { + ids[id] = struct{}{} + } + } + + if profile.Metadata == nil { + return ids + } + + for _, key := range []string{ + "managed_client_ids", + "managedClientIds", + "relying_party_id", + "relyingPartyId", + "client_id", + "clientId", + } { + if raw, ok := profile.Metadata[key]; ok { + addClientIDToSet(ids, raw) + } + } + + return ids +} + +func resolveClientTenantID(summary clientSummary) string { + if summary.Metadata == nil { + return "" + } + clientTenantID, _ := summary.Metadata["tenant_id"].(string) + return strings.TrimSpace(clientTenantID) +} + +func isRPAdminClientAllowed(profile *domain.UserProfileResponse, clientID string) bool { + if normalizeUserRole(profileRole(profile)) != domain.RoleRPAdmin { + return true + } + allowed := managedClientIDsFromProfile(profile) + if len(allowed) == 0 { + return false + } + _, ok := allowed[strings.TrimSpace(clientID)] + return ok +} + +func profileRole(profile *domain.UserProfileResponse) string { + if profile == nil { + return "" + } + return strings.TrimSpace(profile.Role) +} + func (h *DevHandler) checkAppManagerPermission(c *fiber.Ctx) (bool, error) { profile, ok := c.Locals("user_profile").(*domain.UserProfileResponse) if (!ok || profile == nil) && h.Auth != nil { @@ -151,11 +272,19 @@ func (h *DevHandler) checkAppManagerPermission(c *fiber.Ctx) (bool, error) { } } if ok && profile != nil { - // Super Admin bypass - if profile.Role == domain.RoleSuperAdmin { + role := normalizeUserRole(profile.Role) + switch role { + case domain.RoleSuperAdmin: slog.Info("Dev private permission granted by super_admin role", "user_id", profile.ID) return true, nil + case domain.RoleTenantAdmin, domain.RoleRPAdmin: + slog.Info("Dev private permission granted by role", "user_id", profile.ID, "role", role) + return true, nil + case domain.RoleUser: + return false, nil } + + // Super Admin bypass if isAdminEmail(profile.Email) { slog.Info("Dev private permission granted by ADMIN_EMAIL match", "email", profile.Email) return true, nil @@ -203,16 +332,24 @@ func (h *DevHandler) checkAppManagerPermission(c *fiber.Ctx) (bool, error) { if tokenEmail == "" { tokenEmail = strings.TrimSpace(info.Email) } - tokenRole = strings.TrimSpace(info.Role) + tokenRole = normalizeUserRole(info.Role) } else if err != nil { slog.Warn("Dev private permission userinfo fallback failed", "error", err) } } + tokenRole = normalizeUserRole(tokenRole) if tokenRole == domain.RoleSuperAdmin { slog.Info("Dev private permission granted by token role", "role", tokenRole) return true, nil } + if tokenRole == domain.RoleTenantAdmin || tokenRole == domain.RoleRPAdmin { + slog.Info("Dev private permission granted by token role", "role", tokenRole) + return true, nil + } + if tokenRole == domain.RoleUser { + return false, nil + } if isAdminEmail(tokenEmail) { slog.Info("Dev private permission granted by token email", "email", tokenEmail) return true, nil @@ -237,7 +374,7 @@ func (h *DevHandler) checkAppManagerPermission(c *fiber.Ctx) (bool, error) { if h.KratosAdmin != nil { identity, err := h.KratosAdmin.GetIdentity(c.Context(), tokenSubject) if err == nil && identity != nil { - if rawRole, ok := identity.Traits["role"].(string); ok && rawRole == domain.RoleSuperAdmin { + if rawRole, ok := identity.Traits["role"].(string); ok && normalizeUserRole(rawRole) == domain.RoleSuperAdmin { slog.Info("Dev private permission granted by Kratos role", "subject", tokenSubject) return true, nil } @@ -383,90 +520,20 @@ func (h *DevHandler) ListClients(c *fiber.Ctx) error { offset = 0 } - // [Tenant Isolation] Get current user's tenant ID - userTenantID := "" - isSuperAdmin := false - profile, ok := c.Locals("user_profile").(*domain.UserProfileResponse) - if (!ok || profile == nil) && h.Auth != nil { - enriched, _ := h.Auth.GetEnrichedProfile(c) - if enriched != nil { - profile = enriched - ok = true - c.Locals("user_profile", enriched) - } + profile := h.getCurrentProfile(c) + if profile == nil { + return errorJSON(c, fiber.StatusUnauthorized, "unauthorized: authentication required") + } + role := normalizeUserRole(profile.Role) + if !isDevConsoleRoleAllowed(role) { + return errorJSON(c, fiber.StatusForbidden, "forbidden") } - if ok && profile != nil { - if profile.TenantID != nil { - userTenantID = *profile.TenantID - } - isSuperAdmin = profile.Role == domain.RoleSuperAdmin - } else { - // If profile resolution failed, verify bearer token via OIDC userinfo fallback. - authHeader := c.Get("Authorization") - bearerToken := extractBearerToken(authHeader) - if bearerToken == "" { - return errorJSON(c, fiber.StatusUnauthorized, "unauthorized: authentication required") - } - - sub, email := extractAuthClaimsFromBearer(authHeader) - if sub == "" { - info, infoErr := h.fetchOIDCUserInfo(c.Context(), bearerToken) - if infoErr != nil { - slog.Warn("ListClients userinfo fallback failed", "error", infoErr) - return errorJSON(c, fiber.StatusUnauthorized, "unauthorized: authentication required") - } - sub = strings.TrimSpace(info.Sub) - if email == "" { - email = strings.TrimSpace(info.Email) - } - if userTenantID == "" { - userTenantID = strings.TrimSpace(info.TenantID) - } - if strings.EqualFold(strings.TrimSpace(info.Role), domain.RoleSuperAdmin) { - isSuperAdmin = true - } - } - - if sub == "" && email == "" { - return errorJSON(c, fiber.StatusUnauthorized, "unauthorized: authentication required") - } - - if h.KratosAdmin != nil && (userTenantID == "" || !isSuperAdmin) { - identityID := strings.TrimSpace(sub) - if identityID == "" && email != "" { - if resolved, err := h.KratosAdmin.FindIdentityIDByIdentifier(c.Context(), email); err == nil { - identityID = strings.TrimSpace(resolved) - } - } - if identityID != "" { - if identity, err := h.KratosAdmin.GetIdentity(c.Context(), identityID); err == nil && identity != nil { - if userTenantID == "" { - if tid, ok := identity.Traits["tenant_id"].(string); ok { - userTenantID = strings.TrimSpace(tid) - } - } - role := "" - if rawRole, ok := identity.Traits["role"].(string); ok { - role = strings.TrimSpace(rawRole) - } - if role == domain.RoleSuperAdmin { - isSuperAdmin = true - } - profile = &domain.UserProfileResponse{ - ID: identityID, - Email: email, - Role: role, - TenantID: nil, - } - if userTenantID != "" { - tid := userTenantID - profile.TenantID = &tid - } - c.Locals("user_profile", profile) - } - } - } + userTenantID := tenantIDFromProfile(profile) + isSuperAdmin := role == domain.RoleSuperAdmin + allowedClientIDs := managedClientIDsFromProfile(profile) + if role == domain.RoleRPAdmin && len(allowedClientIDs) == 0 { + return errorJSON(c, fiber.StatusForbidden, "forbidden: rp_admin has no managed clients") } isAppManager, err := h.checkAppManagerPermission(c) @@ -503,6 +570,13 @@ func (h *DevHandler) ListClients(c *fiber.Ctx) error { } } + // 3. [Role Scope] RP Admin can only access managed RP IDs + if role == domain.RoleRPAdmin { + if _, ok := allowedClientIDs[summary.ID]; !ok { + continue + } + } + items = append(items, summary) } @@ -529,22 +603,27 @@ func (h *DevHandler) GetClient(c *fiber.Ctx) error { } summary := h.mapClientSummary(*client) + profile := h.getCurrentProfile(c) + if profile == nil { + return errorJSON(c, fiber.StatusUnauthorized, "unauthorized: authentication required") + } + role := normalizeUserRole(profile.Role) + if !isDevConsoleRoleAllowed(role) { + return errorJSON(c, fiber.StatusForbidden, "forbidden") + } // [Tenant Isolation] Check if user has access to this client - isSuperAdmin := false - userTenantID := "" - if profile, ok := c.Locals("user_profile").(*domain.UserProfileResponse); ok && profile != nil { - isSuperAdmin = profile.Role == domain.RoleSuperAdmin - if profile.TenantID != nil { - userTenantID = *profile.TenantID - } - } + isSuperAdmin := role == domain.RoleSuperAdmin + userTenantID := tenantIDFromProfile(profile) if !isSuperAdmin { - clientTenantID, _ := summary.Metadata["tenant_id"].(string) + clientTenantID := resolveClientTenantID(summary) if clientTenantID != userTenantID { return errorJSON(c, fiber.StatusForbidden, "forbidden: access denied to client in another tenant") } } + if !isRPAdminClientAllowed(profile, summary.ID) { + return errorJSON(c, fiber.StatusForbidden, "forbidden: rp_admin scope does not include this client") + } // Check permission for private clients if summary.Type == "private" { @@ -598,22 +677,27 @@ func (h *DevHandler) UpdateClientStatus(c *fiber.Ctx) error { } summary := h.mapClientSummary(*current) + profile := h.getCurrentProfile(c) + if profile == nil { + return errorJSON(c, fiber.StatusUnauthorized, "unauthorized: authentication required") + } + role := normalizeUserRole(profile.Role) + if !isDevConsoleRoleAllowed(role) { + return errorJSON(c, fiber.StatusForbidden, "forbidden") + } // [Tenant Isolation] - isSuperAdmin := false - userTenantID := "" - if profile, ok := c.Locals("user_profile").(*domain.UserProfileResponse); ok && profile != nil { - isSuperAdmin = profile.Role == domain.RoleSuperAdmin - if profile.TenantID != nil { - userTenantID = *profile.TenantID - } - } + isSuperAdmin := role == domain.RoleSuperAdmin + userTenantID := tenantIDFromProfile(profile) if !isSuperAdmin { - clientTenantID, _ := summary.Metadata["tenant_id"].(string) + clientTenantID := resolveClientTenantID(summary) if clientTenantID != userTenantID { return errorJSON(c, fiber.StatusForbidden, "forbidden: access denied to client in another tenant") } } + if !isRPAdminClientAllowed(profile, summary.ID) { + return errorJSON(c, fiber.StatusForbidden, "forbidden: rp_admin scope does not include this client") + } if summary.Type == "private" { isAppManager, _ := h.checkAppManagerPermission(c) @@ -655,6 +739,15 @@ func (h *DevHandler) UpdateClientStatus(c *fiber.Ctx) error { func (h *DevHandler) CreateClient(c *fiber.Ctx) error { tenantID := h.injectTenantContextFromHeader(c) + profile := h.getCurrentProfile(c) + if profile == nil { + return errorJSON(c, fiber.StatusUnauthorized, "unauthorized: authentication required") + } + role := normalizeUserRole(profile.Role) + if !isDevConsoleRoleAllowed(role) { + return errorJSON(c, fiber.StatusForbidden, "forbidden") + } + var req clientUpsertRequest if err := c.BodyParser(&req); err != nil { return errorJSON(c, fiber.StatusBadRequest, "invalid request body") @@ -706,7 +799,7 @@ func (h *DevHandler) CreateClient(c *fiber.Ctx) error { } // [Tenant Isolation] Record owner information - if profile, ok := c.Locals("user_profile").(*domain.UserProfileResponse); ok && profile != nil { + if profile != nil { metadata["user_id"] = profile.ID if tenantID == "" && profile.TenantID != nil { tenantID = *profile.TenantID @@ -805,22 +898,27 @@ func (h *DevHandler) UpdateClient(c *fiber.Ctx) error { } currentSummary := h.mapClientSummary(*current) + profile := h.getCurrentProfile(c) + if profile == nil { + return errorJSON(c, fiber.StatusUnauthorized, "unauthorized: authentication required") + } + role := normalizeUserRole(profile.Role) + if !isDevConsoleRoleAllowed(role) { + return errorJSON(c, fiber.StatusForbidden, "forbidden") + } // [Tenant Isolation] - isSuperAdmin := false - userTenantID := "" - if profile, ok := c.Locals("user_profile").(*domain.UserProfileResponse); ok && profile != nil { - isSuperAdmin = profile.Role == domain.RoleSuperAdmin - if profile.TenantID != nil { - userTenantID = *profile.TenantID - } - } + isSuperAdmin := role == domain.RoleSuperAdmin + userTenantID := tenantIDFromProfile(profile) if !isSuperAdmin { - clientTenantID, _ := currentSummary.Metadata["tenant_id"].(string) + clientTenantID := resolveClientTenantID(currentSummary) if clientTenantID != userTenantID { return errorJSON(c, fiber.StatusForbidden, "forbidden: access denied to client in another tenant") } } + if !isRPAdminClientAllowed(profile, currentSummary.ID) { + return errorJSON(c, fiber.StatusForbidden, "forbidden: rp_admin scope does not include this client") + } clientType := "" if req.Type != nil { @@ -931,22 +1029,27 @@ func (h *DevHandler) DeleteClient(c *fiber.Ctx) error { } summary := h.mapClientSummary(*current) + profile := h.getCurrentProfile(c) + if profile == nil { + return errorJSON(c, fiber.StatusUnauthorized, "unauthorized: authentication required") + } + role := normalizeUserRole(profile.Role) + if !isDevConsoleRoleAllowed(role) { + return errorJSON(c, fiber.StatusForbidden, "forbidden") + } // [Tenant Isolation] - isSuperAdmin := false - userTenantID := "" - if profile, ok := c.Locals("user_profile").(*domain.UserProfileResponse); ok && profile != nil { - isSuperAdmin = profile.Role == domain.RoleSuperAdmin - if profile.TenantID != nil { - userTenantID = *profile.TenantID - } - } + isSuperAdmin := role == domain.RoleSuperAdmin + userTenantID := tenantIDFromProfile(profile) if !isSuperAdmin { - clientTenantID, _ := summary.Metadata["tenant_id"].(string) + clientTenantID := resolveClientTenantID(summary) if clientTenantID != userTenantID { return errorJSON(c, fiber.StatusForbidden, "forbidden: access denied to client in another tenant") } } + if !isRPAdminClientAllowed(profile, summary.ID) { + return errorJSON(c, fiber.StatusForbidden, "forbidden: rp_admin scope does not include this client") + } // [Security] Check permission for private clients if summary.Type == "private" { @@ -986,6 +1089,18 @@ func (h *DevHandler) ListConsents(c *fiber.Ctx) error { return errorJSON(c, fiber.StatusBadRequest, "client_id is required") } + profile := h.getCurrentProfile(c) + if profile == nil { + return errorJSON(c, fiber.StatusUnauthorized, "unauthorized: authentication required") + } + role := normalizeUserRole(profile.Role) + if !isDevConsoleRoleAllowed(role) { + return errorJSON(c, fiber.StatusForbidden, "forbidden") + } + if !isRPAdminClientAllowed(profile, clientID) { + return errorJSON(c, fiber.StatusForbidden, "forbidden: rp_admin scope does not include this client") + } + subject := strings.TrimSpace(c.Query("subject")) limit := c.QueryInt("limit", 50) offset := c.QueryInt("offset", 0) @@ -995,8 +1110,8 @@ func (h *DevHandler) ListConsents(c *fiber.Ctx) error { // [Isolation] Get admin tenant ID from locals or header adminTenantID := "" - if profile, ok := c.Locals("user_profile").(*domain.UserProfileResponse); ok && profile != nil { - if profile.Role != domain.RoleSuperAdmin && profile.TenantID != nil { + if profile != nil { + if role != domain.RoleSuperAdmin && profile.TenantID != nil { adminTenantID = *profile.TenantID } } @@ -1091,6 +1206,17 @@ func (h *DevHandler) RevokeConsents(c *fiber.Ctx) error { return errorJSON(c, fiber.StatusBadRequest, "subject is required") } clientID := strings.TrimSpace(c.Query("client_id")) + profile := h.getCurrentProfile(c) + if profile == nil { + return errorJSON(c, fiber.StatusUnauthorized, "unauthorized: authentication required") + } + role := normalizeUserRole(profile.Role) + if !isDevConsoleRoleAllowed(role) { + return errorJSON(c, fiber.StatusForbidden, "forbidden") + } + if clientID != "" && !isRPAdminClientAllowed(profile, clientID) { + return errorJSON(c, fiber.StatusForbidden, "forbidden: rp_admin scope does not include this client") + } // If subject is not a UUID, try to resolve it as an identifier (email/username) if _, err := uuid.Parse(subject); err != nil { @@ -1138,22 +1264,27 @@ func (h *DevHandler) RotateClientSecret(c *fiber.Ctx) error { } summary := h.mapClientSummary(*current) + profile := h.getCurrentProfile(c) + if profile == nil { + return errorJSON(c, fiber.StatusUnauthorized, "unauthorized: authentication required") + } + role := normalizeUserRole(profile.Role) + if !isDevConsoleRoleAllowed(role) { + return errorJSON(c, fiber.StatusForbidden, "forbidden") + } // [Tenant Isolation] - isSuperAdmin := false - userTenantID := "" - if profile, ok := c.Locals("user_profile").(*domain.UserProfileResponse); ok && profile != nil { - isSuperAdmin = profile.Role == domain.RoleSuperAdmin - if profile.TenantID != nil { - userTenantID = *profile.TenantID - } - } + isSuperAdmin := role == domain.RoleSuperAdmin + userTenantID := tenantIDFromProfile(profile) if !isSuperAdmin { - clientTenantID, _ := summary.Metadata["tenant_id"].(string) + clientTenantID := resolveClientTenantID(summary) if clientTenantID != userTenantID { return errorJSON(c, fiber.StatusForbidden, "forbidden: access denied to client in another tenant") } } + if !isRPAdminClientAllowed(profile, summary.ID) { + return errorJSON(c, fiber.StatusForbidden, "forbidden: rp_admin scope does not include this client") + } // [Security] Check permission for private clients if summary.Type == "private" { @@ -1216,13 +1347,18 @@ func (h *DevHandler) ListAuditLogs(c *fiber.Ctx) error { } h.injectTenantContextFromHeader(c) - allowed, err := h.checkAppManagerPermission(c) - if err != nil { - return errorJSON(c, fiber.StatusInternalServerError, "permission check error") + profile := h.getCurrentProfile(c) + if profile == nil { + return errorJSON(c, fiber.StatusUnauthorized, "unauthorized: authentication required") } - if !allowed { + role := normalizeUserRole(profile.Role) + if !isDevConsoleRoleAllowed(role) { return errorJSON(c, fiber.StatusForbidden, "forbidden") } + allowedClientIDs := managedClientIDsFromProfile(profile) + if role == domain.RoleRPAdmin && len(allowedClientIDs) == 0 { + return errorJSON(c, fiber.StatusForbidden, "forbidden: rp_admin has no managed clients") + } limit := c.QueryInt("limit", 50) if limit <= 0 { @@ -1239,6 +1375,9 @@ func (h *DevHandler) ListAuditLogs(c *fiber.Ctx) error { if tenantFilter == "" { tenantFilter = h.resolveDevTenantScope(c) } + if role != domain.RoleSuperAdmin && tenantFilter == "" { + tenantFilter = tenantIDFromProfile(profile) + } cursorRaw := c.Query("cursor") cursor, err := parseAuditCursor(cursorRaw) @@ -1263,7 +1402,7 @@ func (h *DevHandler) ListAuditLogs(c *fiber.Ctx) error { for _, logItem := range page { scanned++ - if h.matchesDevAuditFilter(logItem, tenantFilter, clientFilter, actionFilter, statusFilter) { + if h.matchesDevAuditFilter(logItem, tenantFilter, clientFilter, actionFilter, statusFilter, allowedClientIDs) { collected = append(collected, logItem) if len(collected) == limit+1 { break @@ -1308,7 +1447,7 @@ func (h *DevHandler) GetStats(c *fiber.Ctx) error { userTenantID := "" isSuperAdmin := false if profile, ok := c.Locals("user_profile").(*domain.UserProfileResponse); ok && profile != nil { - isSuperAdmin = profile.Role == domain.RoleSuperAdmin + isSuperAdmin = normalizeUserRole(profile.Role) == domain.RoleSuperAdmin if profile.TenantID != nil { userTenantID = *profile.TenantID } @@ -1553,6 +1692,7 @@ func clientTypeOrDefault(tokenEndpointAuthMethod string) string { func (h *DevHandler) matchesDevAuditFilter( logItem domain.AuditLog, tenantFilter, clientFilter, actionFilter, statusFilter string, + allowedClientIDs map[string]struct{}, ) bool { if !strings.Contains(logItem.EventType, "/api/v1/dev/") { return false @@ -1574,6 +1714,20 @@ func (h *DevHandler) matchesDevAuditFilter( return false } } + if len(allowedClientIDs) > 0 { + targetID, _ := details["target_id"].(string) + clientID, _ := details["client_id"].(string) + resolvedID := strings.TrimSpace(targetID) + if resolvedID == "" { + resolvedID = strings.TrimSpace(clientID) + } + if resolvedID == "" { + return false + } + if _, ok := allowedClientIDs[resolvedID]; !ok { + return false + } + } if actionFilter != "" { if normalizeAuditAction(logItem.EventType, details) != actionFilter { return false diff --git a/backend/internal/handler/dev_handler_isolation_test.go b/backend/internal/handler/dev_handler_isolation_test.go index e69df93c..ff1f4a05 100644 --- a/backend/internal/handler/dev_handler_isolation_test.go +++ b/backend/internal/handler/dev_handler_isolation_test.go @@ -82,14 +82,14 @@ func TestDevHandler_Isolation(t *testing.T) { app.Use(func(c *fiber.Ctx) error { c.Locals("user_profile", &domain.UserProfileResponse{ ID: "user-a", - Role: domain.RoleUser, + Role: domain.RoleTenantAdmin, TenantID: &tenantA, }) return c.Next() }) app.Get("/api/v1/dev/clients", h.ListClients) - mockKeto.On("CheckPermission", mock.Anything, "user-a", "System", "AppManager", "member").Return(false, nil) + mockKeto.On("CheckPermission", mock.Anything, "user-a", "System", "AppManager", "member").Return(true, nil) req := httptest.NewRequest(http.MethodGet, "/api/v1/dev/clients", nil) resp, _ := app.Test(req, -1) @@ -105,7 +105,7 @@ func TestDevHandler_Isolation(t *testing.T) { assert.Equal(t, "client-tenant-a", res.Items[0].ID) }) - t.Run("GetClient should enforce tenant isolation", func(t *testing.T) { + t.Run("Tenant member should be forbidden from DevFront clients", func(t *testing.T) { app := fiber.New() tenantA := "tenant-a" app.Use(func(c *fiber.Ctx) error { @@ -116,6 +116,52 @@ func TestDevHandler_Isolation(t *testing.T) { }) 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.StatusForbidden, resp.StatusCode) + }) + + t.Run("RP Admin should only see managed clients", func(t *testing.T) { + app := fiber.New() + tenantA := "tenant-a" + app.Use(func(c *fiber.Ctx) error { + c.Locals("user_profile", &domain.UserProfileResponse{ + ID: "rp-admin-a", + Role: domain.RoleRPAdmin, + TenantID: &tenantA, + Metadata: map[string]any{ + "managed_client_ids": []any{"client-tenant-a"}, + }, + }) + 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) + var res struct { + Items []clientSummary `json:"items"` + } + json.NewDecoder(resp.Body).Decode(&res) + assert.Equal(t, 1, len(res.Items)) + assert.Equal(t, "client-tenant-a", res.Items[0].ID) + }) + + t.Run("GetClient should enforce tenant isolation", func(t *testing.T) { + app := fiber.New() + tenantA := "tenant-a" + app.Use(func(c *fiber.Ctx) error { + c.Locals("user_profile", &domain.UserProfileResponse{ + ID: "user-a", + Role: domain.RoleTenantAdmin, + TenantID: &tenantA, + }) + return c.Next() + }) app.Get("/api/v1/dev/clients/:id", h.GetClient) // Case 1: Same tenant @@ -135,7 +181,7 @@ func TestDevHandler_Isolation(t *testing.T) { app.Use(func(c *fiber.Ctx) error { c.Locals("user_profile", &domain.UserProfileResponse{ ID: "user-a", - Role: domain.RoleUser, + Role: domain.RoleTenantAdmin, TenantID: &tenantA, }) return c.Next() diff --git a/backend/internal/handler/dev_handler_test.go b/backend/internal/handler/dev_handler_test.go index 19ede568..d42b99f5 100644 --- a/backend/internal/handler/dev_handler_test.go +++ b/backend/internal/handler/dev_handler_test.go @@ -266,8 +266,6 @@ func TestGetStats_Success(t *testing.T) { } mockKeto := new(devMockKetoService) - // mockKeto setup to allow stats view - mockKeto.On("CheckPermission", mock.Anything, "u1", "System", "AppManager", "member").Return(true, nil) h := &DevHandler{ Hydra: &service.HydraAdminService{ @@ -281,7 +279,7 @@ func TestGetStats_Success(t *testing.T) { tenantID := "t1" app.Use(func(c *fiber.Ctx) error { c.Locals("user_profile", &domain.UserProfileResponse{ - ID: "u1", Role: domain.RoleUser, TenantID: &tenantID, + ID: "u1", Role: domain.RoleTenantAdmin, TenantID: &tenantID, }) return c.Next() }) @@ -297,7 +295,7 @@ func TestGetStats_Success(t *testing.T) { assert.Equal(t, int64(2), res.TotalClients) assert.Equal(t, int64(7), res.AuthFailures) assert.Equal(t, int64(3), res.ActiveSessions) - mockKeto.AssertExpectations(t) + mockKeto.AssertNotCalled(t, "CheckPermission", mock.Anything, mock.Anything, "System", "AppManager", "member") } func TestDevHandler_NoAuditNoAction(t *testing.T) { @@ -323,3 +321,78 @@ func TestDevHandler_NoAuditNoAction(t *testing.T) { 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) +} diff --git a/backend/internal/handler/relying_party_handler.go b/backend/internal/handler/relying_party_handler.go index 4f047f04..600a9490 100644 --- a/backend/internal/handler/relying_party_handler.go +++ b/backend/internal/handler/relying_party_handler.go @@ -44,13 +44,14 @@ func (h *RelyingPartyHandler) ListAll(c *fiber.Ctx) error { var rps []domain.RelyingParty var err error + role := domain.NormalizeRole(profile.Role) - if profile.Role == domain.RoleSuperAdmin { + if role == domain.RoleSuperAdmin { rps, err = h.Service.ListAll(c.Context()) - } else if profile.Role == domain.RoleTenantAdmin && profile.TenantID != nil { + } else if role == domain.RoleTenantAdmin && profile.TenantID != nil { rps, err = h.Service.List(c.Context(), *profile.TenantID) } else { - slog.Warn("Forbidden access to all applications", "userID", profile.ID, "role", profile.Role) + slog.Warn("Forbidden access to all applications", "userID", profile.ID, "role", role) return errorJSON(c, fiber.StatusForbidden, "forbidden: insufficient role to list all applications") } diff --git a/backend/internal/handler/tenant_handler.go b/backend/internal/handler/tenant_handler.go index 56cf1bc4..6ddadc31 100644 --- a/backend/internal/handler/tenant_handler.go +++ b/backend/internal/handler/tenant_handler.go @@ -116,7 +116,7 @@ func (h *TenantHandler) ListTenants(c *fiber.Ctx) error { profile, _ := c.Locals("user_profile").(*domain.UserProfileResponse) // If Tenant Admin, only list manageable tenants - if profile != nil && profile.Role == domain.RoleTenantAdmin { + if profile != nil && domain.NormalizeRole(profile.Role) == domain.RoleTenantAdmin { slog.Info("Listing manageable tenants for tenant admin", "userID", profile.ID) tenants, err = h.Service.ListManageableTenants(c.Context(), profile.ID) if err != nil { diff --git a/backend/internal/handler/user_handler.go b/backend/internal/handler/user_handler.go index 45d36730..acaa4eac 100644 --- a/backend/internal/handler/user_handler.go +++ b/backend/internal/handler/user_handler.go @@ -61,7 +61,7 @@ func (h *UserHandler) ListUsers(c *fiber.Ctx) error { var requesterRole string var requesterCompany string if profile, ok := c.Locals("user_profile").(*domain.UserProfileResponse); ok { - requesterRole = profile.Role + requesterRole = domain.NormalizeRole(profile.Role) requesterCompany = profile.CompanyCode } @@ -195,7 +195,7 @@ func (h *UserHandler) GetUser(c *fiber.Ctx) error { // [New] Check access scope requester, _ := c.Locals("user_profile").(*domain.UserProfileResponse) - if requester != nil && requester.Role == domain.RoleTenantAdmin { + if requester != nil && domain.NormalizeRole(requester.Role) == domain.RoleTenantAdmin { compCode := extractTraitString(identity.Traits, "companyCode") if requester.CompanyCode == "" || compCode != requester.CompanyCode { return errorJSON(c, fiber.StatusForbidden, "forbidden: access to user in another tenant denied") @@ -263,9 +263,9 @@ func (h *UserHandler) CreateUser(c *fiber.Ctx) error { } } - role := strings.TrimSpace(req.Role) + role := domain.NormalizeRole(req.Role) if role == "" { - role = "user" + role = domain.RoleUser } attributes := map[string]interface{}{ @@ -380,7 +380,7 @@ func (h *UserHandler) UpdateUser(c *fiber.Ctx) error { // [New] Check access scope requester, _ := c.Locals("user_profile").(*domain.UserProfileResponse) - if requester != nil && requester.Role == domain.RoleTenantAdmin { + if requester != nil && domain.NormalizeRole(requester.Role) == domain.RoleTenantAdmin { compCode := extractTraitString(identity.Traits, "companyCode") if requester.CompanyCode == "" || compCode != requester.CompanyCode { return errorJSON(c, fiber.StatusForbidden, "forbidden: cannot update user in another tenant") @@ -402,7 +402,7 @@ func (h *UserHandler) UpdateUser(c *fiber.Ctx) error { } // [New] Tenant Admin restriction: Cannot change companyCode - if requester != nil && requester.Role == domain.RoleTenantAdmin { + if requester != nil && domain.NormalizeRole(requester.Role) == domain.RoleTenantAdmin { if req.CompanyCode != nil && *req.CompanyCode != requester.CompanyCode { return errorJSON(c, fiber.StatusForbidden, "forbidden: tenant admins cannot change user's tenant") } @@ -437,9 +437,9 @@ func (h *UserHandler) UpdateUser(c *fiber.Ctx) error { traits["department"] = strings.TrimSpace(*req.Department) } if req.Role != nil { - role := strings.TrimSpace(*req.Role) + role := domain.NormalizeRole(*req.Role) if role == "" { - role = "user" + role = domain.RoleUser } traits["grade"] = role traits["role"] = role @@ -507,7 +507,7 @@ func (h *UserHandler) DeleteUser(c *fiber.Ctx) error { // [New] Check access scope before deletion requester, _ := c.Locals("user_profile").(*domain.UserProfileResponse) - if requester != nil && requester.Role == domain.RoleTenantAdmin { + if requester != nil && domain.NormalizeRole(requester.Role) == domain.RoleTenantAdmin { identity, err := h.KratosAdmin.GetIdentity(c.Context(), userID) if err == nil && identity != nil { compCode := extractTraitString(identity.Traits, "companyCode") @@ -541,7 +541,11 @@ func (h *UserHandler) mapIdentitySummary(ctx context.Context, identity service.K traits := identity.Traits role := extractTraitString(traits, "grade") if role == "" { - role = "user" + role = extractTraitString(traits, "role") + } + role = domain.NormalizeRole(role) + if role == "" { + role = domain.RoleUser } compCode := extractTraitString(traits, "companyCode") @@ -589,7 +593,11 @@ func (h *UserHandler) mapToLocalUser(identity service.KratosIdentity) *domain.Us traits := identity.Traits role := extractTraitString(traits, "grade") if role == "" { - role = "user" + role = extractTraitString(traits, "role") + } + role = domain.NormalizeRole(role) + if role == "" { + role = domain.RoleUser } compCode := extractTraitString(traits, "companyCode") @@ -633,6 +641,9 @@ func (h *UserHandler) mapToLocalUser(identity service.KratosIdentity) *domain.Us } func (h *UserHandler) syncKetoRole(ctx context.Context, userID, newRole, oldRole, oldTenantID string, newTenantID *string) { + newRole = domain.NormalizeRole(newRole) + oldRole = domain.NormalizeRole(oldRole) + // Remove old roles if oldRole == domain.RoleSuperAdmin { _ = h.KetoOutboxRepo.Create(ctx, &domain.KetoOutbox{ diff --git a/backend/internal/middleware/rbac.go b/backend/internal/middleware/rbac.go index aaa345ab..5a15e190 100644 --- a/backend/internal/middleware/rbac.go +++ b/backend/internal/middleware/rbac.go @@ -31,8 +31,10 @@ func RequireKetoPermission(config RBACConfig, namespace, relation string) fiber. // Store profile in locals for further use in handlers c.Locals("user_profile", profile) + role := domain.NormalizeRole(profile.Role) + // Super Admin bypass - if profile.Role == domain.RoleSuperAdmin { + if role == domain.RoleSuperAdmin { return c.Next() } @@ -67,7 +69,7 @@ func RequireKetoPermission(config RBACConfig, namespace, relation string) fiber. } if !allowed { - slog.Warn("Keto permission denied", "userID", profile.ID, "userRole", profile.Role, "namespace", namespace, "objectID", objectID, "relation", relation, "X-Test-Role", c.Get("X-Test-Role")) + slog.Warn("Keto permission denied", "userID", profile.ID, "userRole", role, "namespace", namespace, "objectID", objectID, "relation", relation, "X-Test-Role", c.Get("X-Test-Role")) return errorJSON(c, fiber.StatusForbidden, "forbidden: keto permission denied for "+namespace+":"+objectID) } @@ -91,15 +93,17 @@ func RequireRole(config RBACConfig) fiber.Handler { // Store profile in locals for further use in handlers c.Locals("user_profile", profile) + userRole := domain.NormalizeRole(profile.Role) + // Super Admin always has access - if profile.Role == domain.RoleSuperAdmin { + if userRole == domain.RoleSuperAdmin { return c.Next() } // Check if user's role is in allowed roles roleAllowed := false for _, role := range config.AllowedRoles { - if profile.Role == role { + if userRole == domain.NormalizeRole(role) { roleAllowed = true break } @@ -108,7 +112,7 @@ func RequireRole(config RBACConfig) fiber.Handler { if !roleAllowed { slog.Warn("RBAC access denied", "userID", profile.ID, - "userRole", profile.Role, + "userRole", userRole, "allowedRoles", config.AllowedRoles, "path", c.Path(), "X-Test-Role", c.Get("X-Test-Role"), @@ -136,13 +140,15 @@ func RequireTenantMatch(config RBACConfig) fiber.Handler { // Store profile in locals for further use in handlers c.Locals("user_profile", profile) + userRole := domain.NormalizeRole(profile.Role) + // Super Admin bypass - if profile.Role == domain.RoleSuperAdmin { + if userRole == domain.RoleSuperAdmin { return c.Next() } // Tenant Admin check - if profile.Role == domain.RoleTenantAdmin { + if userRole == domain.RoleTenantAdmin { targetTenantID := c.Params("tenantId") if targetTenantID == "" { targetTenantID = c.Params("id") // common for /tenants/:id From 95ae991af4d4e7c5a77d36f41af254b63b0b280c Mon Sep 17 00:00:00 2001 From: kyy Date: Mon, 16 Mar 2026 15:08:55 +0900 Subject: [PATCH 08/11] =?UTF-8?q?E2E=20=EC=97=AD=ED=95=A0=20=EC=A0=84?= =?UTF-8?q?=ED=99=98=20=ED=85=8C=EC=8A=A4=ED=8A=B8=20=EB=A0=88=EC=9D=B4?= =?UTF-8?q?=EC=8A=A4=20=EC=BB=A8=EB=94=94=EC=85=98=20=ED=95=B4=EA=B2=B0=20?= =?UTF-8?q?=EB=B0=8F=20=EC=95=88=EC=A0=95=EC=84=B1=20=EB=B3=B4=EA=B0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- devfront/tests/devfront-role-switch-report.spec.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/devfront/tests/devfront-role-switch-report.spec.ts b/devfront/tests/devfront-role-switch-report.spec.ts index 794564d7..6fcf659d 100644 --- a/devfront/tests/devfront-role-switch-report.spec.ts +++ b/devfront/tests/devfront-role-switch-report.spec.ts @@ -93,7 +93,10 @@ test.describe("DevFront role report", () => { await page .getByPlaceholder("My Awesome Application") .fill("Tenant A CRM Updated"); + + const updatePromise = page.waitForResponse(r => r.url().includes('/api/v1/dev/clients') && r.request().method() === 'PUT'); await page.getByRole("button", { name: /^저장$|^Save$/i }).click(); + await updatePromise; await page.goto("/audit-logs"); await expect(page.getByText("UPDATE_CLIENT")).toBeVisible({ @@ -130,7 +133,10 @@ test.describe("DevFront role report", () => { await page .getByPlaceholder(/https:\/\/app\.example\.com\/callback/i) .fill("https://super-admin.example.com/callback"); + + const createPromise = page.waitForResponse(r => r.url().includes('/api/v1/dev/clients') && r.request().method() === 'POST'); await page.getByRole("button", { name: /앱 생성|Create/i }).click(); + await createPromise; await page.goto("/audit-logs"); await expect(page.getByText("CREATE_CLIENT")).toBeVisible({ From 1ff12075f6c44dbae6a03802133e459ddc773f4f Mon Sep 17 00:00:00 2001 From: kyy Date: Mon, 16 Mar 2026 15:34:27 +0900 Subject: [PATCH 09/11] =?UTF-8?q?[#365]=20Devfront=20=ED=94=84=EB=A1=9C?= =?UTF-8?q?=ED=95=84=20=EB=A9=94=EB=89=B4=20=EA=B0=9C=EC=84=A0=20=EB=B0=8F?= =?UTF-8?q?=20=EC=83=81=EC=84=B8=20=ED=8E=98=EC=9D=B4=EC=A7=80=20=EA=B5=AC?= =?UTF-8?q?=ED=98=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- devfront/src/app/routes.tsx | 2 + devfront/src/components/layout/AppLayout.tsx | 50 ++++- .../features/clients/ClientConsentsPage.tsx | 2 +- devfront/src/features/clients/ClientsPage.tsx | 4 +- devfront/src/features/profile/ProfilePage.tsx | 186 ++++++++++++++++++ devfront/src/locales/en.toml | 30 +++ devfront/src/locales/ko.toml | 30 +++ devfront/src/locales/template.toml | 30 +++ 8 files changed, 324 insertions(+), 10 deletions(-) create mode 100644 devfront/src/features/profile/ProfilePage.tsx diff --git a/devfront/src/app/routes.tsx b/devfront/src/app/routes.tsx index b28a124c..1586062e 100644 --- a/devfront/src/app/routes.tsx +++ b/devfront/src/app/routes.tsx @@ -8,6 +8,7 @@ import ClientConsentsPage from "../features/clients/ClientConsentsPage"; import ClientDetailsPage from "../features/clients/ClientDetailsPage"; import ClientGeneralPage from "../features/clients/ClientGeneralPage"; import ClientsPage from "../features/clients/ClientsPage"; +import ProfilePage from "../features/profile/ProfilePage"; export const router = createBrowserRouter( [ @@ -33,6 +34,7 @@ export const router = createBrowserRouter( { path: "clients/:id/consents", element: }, { path: "clients/:id/settings", element: }, { path: "audit-logs", element: }, + { path: "profile", element: }, ], }, ], diff --git a/devfront/src/components/layout/AppLayout.tsx b/devfront/src/components/layout/AppLayout.tsx index 92b458a8..cdb98dcb 100644 --- a/devfront/src/components/layout/AppLayout.tsx +++ b/devfront/src/components/layout/AppLayout.tsx @@ -1,3 +1,4 @@ +import { useQuery } from "@tanstack/react-query"; import { BadgeCheck, LogOut, @@ -5,6 +6,7 @@ import { NotebookTabs, ShieldHalf, Sun, + User as UserIcon, } from "lucide-react"; import { useEffect, useRef, useState } from "react"; import { useAuth } from "react-oidc-context"; @@ -13,6 +15,8 @@ import { t } from "../../lib/i18n"; import { resolveProfileRole } from "../../lib/role"; import LanguageSelector from "../common/LanguageSelector"; import { Toaster } from "../ui/toaster"; +import { Badge } from "../ui/badge"; +import { fetchMe } from "../../features/auth/authApi"; const navItems = [ { @@ -41,6 +45,13 @@ function AppLayout() { const [isRefreshingSession, setIsRefreshingSession] = useState(false); const [nowMs, setNowMs] = useState(() => Date.now()); + const hasAccessToken = Boolean(auth.user?.access_token); + const { data: profile } = useQuery({ + queryKey: ["userMe"], + queryFn: fetchMe, + enabled: hasAccessToken, + }); + const handleLogout = () => { if (window.confirm(t("msg.dev.logout_confirm", "로그아웃 하시겠습니까?"))) { auth.removeUser(); @@ -100,6 +111,10 @@ function AppLayout() { const currentRole = resolveProfileRole( auth.user?.profile as Record | undefined, ); + + // Use profile.role from API if available, otherwise fallback to local role + const displayRoleKey = profile?.role || currentRole; + const isDevConsoleAllowed = [ "super_admin", "tenant_admin", @@ -306,14 +321,35 @@ function AppLayout() {

{t("ui.dev.profile.menu_title", "Account")}

-
-

- {profileName} -

-

- {profileEmail} -

+
+
+

+ {profileName} +

+

+ {profileEmail} +

+
+
+ + {t(`ui.common.role.${displayRoleKey}`, displayRoleKey.toUpperCase())} + +
+ + +
+ + + +
+ {activeTab === "basic" && ( +
+ + + + + {t("ui.dev.profile.basic.title", "사용자 정보")} + + + +
+

+ + {t("ui.dev.profile.basic.id", "User ID")} +

+

+ {profile.id} +

+
+
+

+ + {t("ui.dev.profile.basic.name", "Name")} +

+

{profile.name}

+
+
+

+ + {t("ui.dev.profile.basic.email", "Email")} +

+

{profile.email}

+
+
+
+ + + + + + {t("ui.dev.profile.org.title", "조직 정보")} + + + +
+

+ {t("ui.dev.profile.org.tenant", "테넌트")} +

+

+ {displayTenant} +

+
+
+

+ {t("ui.dev.profile.org.company_code", "회사 코드")} +

+

{displayCompanyCode}

+
+
+
+
+ )} + + {activeTab === "role" && ( + + + + + {t("ui.dev.profile.role.title", "시스템 역할")} + + + {t( + "ui.dev.profile.role.description", + "현재 계정에 부여된 권한 등급입니다.", + )} + + + +
+
+ +
+
+

+ {t("ui.dev.profile.role.current", "Current Role")} +

+

+ {t(`ui.common.role.${profile.role}`, profile.role.toUpperCase())} +

+
+
+
+
+ )} +
+ + ); +} + +export default ProfilePage; diff --git a/devfront/src/locales/en.toml b/devfront/src/locales/en.toml index 6936c8b2..ceaea07d 100644 --- a/devfront/src/locales/en.toml +++ b/devfront/src/locales/en.toml @@ -1399,6 +1399,36 @@ verify = "Verify" [ui.userfront.signup.success] action = "Action" +[ui.dev.profile] +unknown_name = "Unknown User" +unknown_email = "unknown@example.com" +menu_aria = "Open account menu" +menu_title = "Account" +title = "Profile" +subtitle = "View user details and assigned roles." +loading = "Loading profile..." +error = "Failed to load profile." + +[ui.dev.profile.tab] +basic = "Basic Info" +role = "Roles & Permissions" + +[ui.dev.profile.basic] +title = "User Info" +id = "User ID" +name = "Name" +email = "Email" + +[ui.dev.profile.org] +title = "Organization Info" +tenant = "Tenant" +company_code = "Company Code" + +[ui.dev.profile.role] +title = "System Role" +description = "The permission level granted to this account." +current = "Current Role" + [ui.admin.nav] api_keys = "API Keys" audit_logs = "Audit Logs" diff --git a/devfront/src/locales/ko.toml b/devfront/src/locales/ko.toml index 3879ffd8..eb34ab28 100644 --- a/devfront/src/locales/ko.toml +++ b/devfront/src/locales/ko.toml @@ -1411,3 +1411,33 @@ tenant_dashboard = "테넌트 대시보드" user_groups = "유저 그룹" tenants = "테넌트" users = "사용자" + +[ui.dev.profile] +unknown_name = "알 수 없는 사용자" +unknown_email = "unknown@example.com" +menu_aria = "계정 메뉴 열기" +menu_title = "Account" +title = "내 정보" +subtitle = "사용자 상세 정보 및 할당된 역할(Role)을 확인합니다." +loading = "프로필 정보를 불러오는 중..." +error = "프로필 정보를 불러오지 못했습니다." + +[ui.dev.profile.tab] +basic = "기본 정보" +role = "권한 및 역할" + +[ui.dev.profile.basic] +title = "사용자 정보" +id = "사용자 ID" +name = "이름" +email = "이메일" + +[ui.dev.profile.org] +title = "조직 정보" +tenant = "테넌트" +company_code = "회사 코드" + +[ui.dev.profile.role] +title = "시스템 역할" +description = "현재 계정에 부여된 권한 등급입니다." +current = "현재 역할" diff --git a/devfront/src/locales/template.toml b/devfront/src/locales/template.toml index d3fa256f..4afd8a93 100644 --- a/devfront/src/locales/template.toml +++ b/devfront/src/locales/template.toml @@ -1410,3 +1410,33 @@ verify = "" [ui.userfront.signup.success] action = "" + +[ui.dev.profile] +unknown_name = "" +unknown_email = "" +menu_aria = "" +menu_title = "" +title = "" +subtitle = "" +loading = "" +error = "" + +[ui.dev.profile.tab] +basic = "" +role = "" + +[ui.dev.profile.basic] +title = "" +id = "" +name = "" +email = "" + +[ui.dev.profile.org] +title = "" +tenant = "" +company_code = "" + +[ui.dev.profile.role] +title = "" +description = "" +current = "" From 9a4681b2c053716ead3df9ac107eaf967f28d23b Mon Sep 17 00:00:00 2001 From: kyy Date: Mon, 16 Mar 2026 16:16:53 +0900 Subject: [PATCH 10/11] =?UTF-8?q?=EB=82=B4=20=EC=A0=95=EB=B3=B4=20?= =?UTF-8?q?=EB=B0=8F=20=EC=97=AD=ED=95=A0=EB=B3=84=20=EA=B6=8C=ED=95=9C=20?= =?UTF-8?q?=EB=B2=94=EC=9C=84=20=EC=95=88=EB=82=B4=20=EC=A0=9C=EA=B3=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- devfront/src/features/profile/ProfilePage.tsx | 17 +++++++++++++++-- devfront/src/locales/en.toml | 6 ++++++ devfront/src/locales/ko.toml | 6 ++++++ devfront/src/locales/template.toml | 6 ++++++ 4 files changed, 33 insertions(+), 2 deletions(-) diff --git a/devfront/src/features/profile/ProfilePage.tsx b/devfront/src/features/profile/ProfilePage.tsx index 6e026ffc..e4917363 100644 --- a/devfront/src/features/profile/ProfilePage.tsx +++ b/devfront/src/features/profile/ProfilePage.tsx @@ -117,6 +117,13 @@ function ProfilePage() {

{profile.email}

+
+

+ + {t("ui.dev.profile.basic.phone", "Phone")} +

+

{profile.phone || "-"}

+
@@ -163,16 +170,22 @@ function ProfilePage() {
-
+
-
+

{t("ui.dev.profile.role.current", "Current Role")}

{t(`ui.common.role.${profile.role}`, profile.role.toUpperCase())}

+

+ {t( + `ui.dev.profile.role.desc_${profile.role}`, + "시스템 역할에 대한 설명이 제공되지 않았습니다.", + )} +

diff --git a/devfront/src/locales/en.toml b/devfront/src/locales/en.toml index ceaea07d..665aa6cd 100644 --- a/devfront/src/locales/en.toml +++ b/devfront/src/locales/en.toml @@ -1418,6 +1418,7 @@ title = "User Info" id = "User ID" name = "Name" email = "Email" +phone = "Phone Number" [ui.dev.profile.org] title = "Organization Info" @@ -1428,6 +1429,11 @@ company_code = "Company Code" title = "System Role" description = "The permission level granted to this account." current = "Current Role" +desc_super_admin = "Can manage all tenants and applications system-wide without restriction." +desc_tenant_admin = "Can manage all applications within their assigned tenant." +desc_rp_admin = "Can view and manage only assigned/linked applications." +desc_user = "Standard application access. DevFront access is denied." +desc_tenant_member = "Standard application access. DevFront access is denied." [ui.admin.nav] api_keys = "API Keys" diff --git a/devfront/src/locales/ko.toml b/devfront/src/locales/ko.toml index eb34ab28..74a27993 100644 --- a/devfront/src/locales/ko.toml +++ b/devfront/src/locales/ko.toml @@ -1431,6 +1431,7 @@ title = "사용자 정보" id = "사용자 ID" name = "이름" email = "이메일" +phone = "전화번호" [ui.dev.profile.org] title = "조직 정보" @@ -1441,3 +1442,8 @@ company_code = "회사 코드" title = "시스템 역할" description = "현재 계정에 부여된 권한 등급입니다." current = "현재 역할" +desc_super_admin = "전체 시스템의 모든 테넌트와 모든 앱을 제한 없이 관리할 수 있습니다." +desc_tenant_admin = "본인이 속한 테넌트(조직/회사) 하위의 모든 앱을 관리할 수 있습니다." +desc_rp_admin = "본인에게 할당된 연동 앱(Client)만 확인 및 관리할 수 있습니다." +desc_user = "기본 앱 이용 권한을 가지며, DevFront 접근은 차단됩니다." +desc_tenant_member = "기본 앱 이용 권한을 가지며, DevFront 접근은 차단됩니다." diff --git a/devfront/src/locales/template.toml b/devfront/src/locales/template.toml index 4afd8a93..1da1c1ac 100644 --- a/devfront/src/locales/template.toml +++ b/devfront/src/locales/template.toml @@ -1430,6 +1430,7 @@ title = "" id = "" name = "" email = "" +phone = "" [ui.dev.profile.org] title = "" @@ -1440,3 +1441,8 @@ company_code = "" title = "" description = "" current = "" +desc_super_admin = "" +desc_tenant_admin = "" +desc_rp_admin = "" +desc_user = "" +desc_tenant_member = "" From fb27fbf3b1c6a6930bcf5185ca46cbdfee0f0550 Mon Sep 17 00:00:00 2001 From: kyy Date: Mon, 16 Mar 2026 16:43:25 +0900 Subject: [PATCH 11/11] =?UTF-8?q?i18n=20=EB=88=84=EB=9D=BD=20=ED=82=A4=20?= =?UTF-8?q?=EB=B3=B4=EC=99=84=20=EB=B0=8F=20biome=20=ED=8F=AC=EB=A7=B7=20?= =?UTF-8?q?=EC=A0=95=EB=A6=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- devfront/src/components/layout/AppLayout.tsx | 16 ++++++--- devfront/src/features/profile/ProfilePage.tsx | 33 ++++++++++++++----- devfront/src/lib/role.ts | 4 ++- .../tests/devfront-role-switch-report.spec.ts | 16 ++++++--- locales/en.toml | 25 ++++++++++++++ locales/ko.toml | 25 ++++++++++++++ locales/template.toml | 25 ++++++++++++++ 7 files changed, 126 insertions(+), 18 deletions(-) diff --git a/devfront/src/components/layout/AppLayout.tsx b/devfront/src/components/layout/AppLayout.tsx index cdb98dcb..64ed2759 100644 --- a/devfront/src/components/layout/AppLayout.tsx +++ b/devfront/src/components/layout/AppLayout.tsx @@ -111,7 +111,7 @@ function AppLayout() { const currentRole = resolveProfileRole( auth.user?.profile as Record | undefined, ); - + // Use profile.role from API if available, otherwise fallback to local role const displayRoleKey = profile?.role || currentRole; @@ -331,12 +331,18 @@ function AppLayout() {

- - {t(`ui.common.role.${displayRoleKey}`, displayRoleKey.toUpperCase())} + + {t( + `ui.common.role.${displayRoleKey}`, + displayRoleKey.toUpperCase(), + )}
- + - +