forked from baron/baron-sso
Merge pull request 'test/df-authz' (#364) from test/df-authz into dev
Reviewed-on: baron/baron-sso#364
This commit is contained in:
@@ -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) {
|
func (m *AsyncMockTenantService) ListManageableTenants(ctx context.Context, userID string) ([]domain.Tenant, error) {
|
||||||
return nil, nil
|
return nil, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *AsyncMockTenantService) IsDomainAllowed(ctx context.Context, domainName string) (bool, error) {
|
func (m *AsyncMockTenantService) IsDomainAllowed(ctx context.Context, domainName string) (bool, error) {
|
||||||
return false, nil
|
return false, nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func TestDevHandler_Isolation(t *testing.T) {
|
func TestDevHandler_Isolation(t *testing.T) {
|
||||||
mockKeto := new(MockKetoService)
|
mockKeto := new(devMockKetoService)
|
||||||
|
|
||||||
h := &DevHandler{
|
h := &DevHandler{
|
||||||
Hydra: &service.HydraAdminService{
|
Hydra: &service.HydraAdminService{
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import (
|
|||||||
"bytes"
|
"bytes"
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/http/httptest"
|
"net/http/httptest"
|
||||||
"testing"
|
"testing"
|
||||||
@@ -16,33 +17,79 @@ import (
|
|||||||
"github.com/stretchr/testify/mock"
|
"github.com/stretchr/testify/mock"
|
||||||
)
|
)
|
||||||
|
|
||||||
type MockKetoService struct {
|
// --- Mocks with Unique Names to Avoid Collisions ---
|
||||||
|
|
||||||
|
type devMockKetoService struct {
|
||||||
mock.Mock
|
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)
|
args := m.Called(ctx, subject, namespace, object, relation)
|
||||||
return args.Bool(0), args.Error(1)
|
return args.Bool(0), args.Error(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *MockKetoService) CreateRelation(ctx context.Context, namespace, object, relation, subject string) error {
|
func (m *devMockKetoService) CreateRelation(ctx context.Context, ns, obj, rel, sub string) error {
|
||||||
return m.Called(ctx, namespace, object, relation, subject).Error(0)
|
return m.Called(ctx, ns, obj, rel, sub).Error(0)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *MockKetoService) DeleteRelation(ctx context.Context, namespace, object, relation, subject string) error {
|
func (m *devMockKetoService) DeleteRelation(ctx context.Context, ns, obj, rel, sub string) error {
|
||||||
return m.Called(ctx, namespace, object, relation, subject).Error(0)
|
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) {
|
func (m *devMockKetoService) ListRelations(ctx context.Context, ns, obj, rel, sub string) ([]service.RelationTuple, error) {
|
||||||
args := m.Called(ctx, namespace, object, relation, subject)
|
args := m.Called(ctx, ns, obj, rel, sub)
|
||||||
return args.Get(0).([]service.RelationTuple), args.Error(1)
|
return args.Get(0).([]service.RelationTuple), args.Error(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *MockKetoService) ListObjects(ctx context.Context, namespace, relation, subject string) ([]string, error) {
|
func (m *devMockKetoService) ListObjects(ctx context.Context, ns, rel, sub string) ([]string, error) {
|
||||||
args := m.Called(ctx, namespace, relation, subject)
|
args := m.Called(ctx, ns, rel, sub)
|
||||||
return args.Get(0).([]string), args.Error(1)
|
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) {
|
func TestListClients_Success(t *testing.T) {
|
||||||
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
||||||
if r.URL.Path == "/clients" {
|
if r.URL.Path == "/clients" {
|
||||||
@@ -51,11 +98,10 @@ func TestListClients_Success(t *testing.T) {
|
|||||||
{"client_id": "client-2", "client_name": "App Two", "metadata": map[string]interface{}{"status": "inactive"}},
|
{"client_id": "client-2", "client_name": "App Two", "metadata": map[string]interface{}{"status": "inactive"}},
|
||||||
}), nil
|
}), nil
|
||||||
}
|
}
|
||||||
return httpJSONAny(r, http.StatusNotFound, map[string]string{"error": "not found"}), nil
|
return httpJSONAny(r, http.StatusNotFound, nil), nil
|
||||||
})
|
})
|
||||||
|
|
||||||
mockKeto := new(MockKetoService)
|
mockKeto := new(devMockKetoService)
|
||||||
// For simplicity, always allow in basic success test
|
|
||||||
mockKeto.On("CheckPermission", mock.Anything, mock.Anything, "System", "AppManager", "member").Return(true, nil)
|
mockKeto.On("CheckPermission", mock.Anything, mock.Anything, "System", "AppManager", "member").Return(true, nil)
|
||||||
|
|
||||||
h := &DevHandler{
|
h := &DevHandler{
|
||||||
@@ -76,72 +122,61 @@ func TestListClients_Success(t *testing.T) {
|
|||||||
resp, _ := app.Test(req, -1)
|
resp, _ := app.Test(req, -1)
|
||||||
|
|
||||||
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
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) {
|
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{}{
|
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
|
||||||
"client_id": "client-123",
|
"client_id": "client-1", "metadata": map[string]interface{}{"status": "active"},
|
||||||
"client_name": "Test App",
|
|
||||||
"metadata": map[string]interface{}{"status": "active"},
|
|
||||||
}), nil
|
}), 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{
|
h := &DevHandler{
|
||||||
Hydra: &service.HydraAdminService{
|
Hydra: &service.HydraAdminService{
|
||||||
AdminURL: "http://hydra.test",
|
AdminURL: "http://hydra.test",
|
||||||
PublicURL: "http://hydra-public.test", // PublicURL 추가
|
|
||||||
HTTPClient: &http.Client{Transport: transport},
|
HTTPClient: &http.Client{Transport: transport},
|
||||||
},
|
},
|
||||||
Keto: mockKeto,
|
Keto: new(devMockKetoService),
|
||||||
}
|
}
|
||||||
app := fiber.New()
|
app := fiber.New()
|
||||||
app.Use(func(c *fiber.Ctx) error {
|
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()
|
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)
|
resp, _ := app.Test(req, -1)
|
||||||
|
|
||||||
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
||||||
|
|
||||||
var res clientDetailResponse
|
var res clientDetailResponse
|
||||||
json.NewDecoder(resp.Body).Decode(&res)
|
json.NewDecoder(resp.Body).Decode(&res)
|
||||||
assert.Equal(t, "client-123", res.Client.ID)
|
assert.Equal(t, "inactive", res.Client.Status)
|
||||||
assert.Equal(t, "Test App", res.Client.Name)
|
|
||||||
assert.Equal(t, "http://hydra-public.test/oauth2/auth", res.Endpoints.Authorization)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCreateClient_Success(t *testing.T) {
|
func TestDeleteClient_Success(t *testing.T) {
|
||||||
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
||||||
if r.Method == http.MethodPost && r.URL.Path == "/clients" {
|
if r.Method == http.MethodGet && r.URL.Path == "/clients/client-1" {
|
||||||
return httpJSONAny(r, http.StatusCreated, map[string]interface{}{
|
return httpJSONAny(r, http.StatusOK, map[string]interface{}{"client_id": "client-1"}), nil
|
||||||
"client_id": "new-client-123",
|
|
||||||
"client_name": "New App",
|
|
||||||
"client_secret": "secret-123",
|
|
||||||
}), 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: map[string]string{"client-1": "secret"}}
|
||||||
secretRepo := &mockSecretRepo{secrets: make(map[string]string)}
|
redisRepo := &devMockRedisRepo{data: map[string]string{"client_secret:client-1": "secret"}}
|
||||||
redisRepo := &mockRedisRepo{data: make(map[string]string)}
|
|
||||||
|
|
||||||
h := &DevHandler{
|
h := &DevHandler{
|
||||||
Hydra: &service.HydraAdminService{
|
Hydra: &service.HydraAdminService{
|
||||||
@@ -150,102 +185,141 @@ func TestCreateClient_Success(t *testing.T) {
|
|||||||
},
|
},
|
||||||
SecretRepo: secretRepo,
|
SecretRepo: secretRepo,
|
||||||
Redis: redisRepo,
|
Redis: redisRepo,
|
||||||
Keto: mockKeto,
|
Keto: new(devMockKetoService),
|
||||||
}
|
}
|
||||||
app := fiber.New()
|
app := fiber.New()
|
||||||
app.Use(func(c *fiber.Ctx) error {
|
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()
|
return c.Next()
|
||||||
})
|
})
|
||||||
app.Post("/api/v1/dev/clients", h.CreateClient)
|
app.Delete("/api/v1/dev/clients/:id", h.DeleteClient)
|
||||||
|
|
||||||
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")
|
|
||||||
|
|
||||||
|
req := httptest.NewRequest(http.MethodDelete, "/api/v1/dev/clients/client-1", nil)
|
||||||
resp, _ := app.Test(req, -1)
|
resp, _ := app.Test(req, -1)
|
||||||
assert.Equal(t, http.StatusCreated, resp.StatusCode)
|
|
||||||
|
|
||||||
secret, _ := secretRepo.GetByID(nil, "new-client-123")
|
assert.Equal(t, http.StatusNoContent, resp.StatusCode)
|
||||||
assert.Equal(t, "secret-123", secret)
|
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) {
|
func TestRotateClientSecret_Success(t *testing.T) {
|
||||||
now := time.Now().UTC()
|
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
||||||
auditRepo := &mockAuditRepo{
|
if r.Method == http.MethodGet && r.URL.Path == "/clients/client-1" {
|
||||||
logs: []domain.AuditLog{
|
return httpJSONAny(r, http.StatusOK, map[string]interface{}{"client_id": "client-1"}), nil
|
||||||
{
|
}
|
||||||
EventID: "evt-1",
|
if r.Method == http.MethodPut && r.URL.Path == "/clients/client-1" {
|
||||||
Timestamp: now,
|
var body map[string]interface{}
|
||||||
UserID: "user-a",
|
json.NewDecoder(r.Body).Decode(&body)
|
||||||
EventType: "PUT /api/v1/dev/clients/client-1",
|
return httpJSONAny(r, http.StatusOK, body), nil
|
||||||
Status: "success",
|
}
|
||||||
Details: `{"action":"UPDATE_CLIENT","target_id":"client-1","tenant_id":"tenant-a"}`,
|
return httpJSONAny(r, http.StatusNotFound, nil), nil
|
||||||
},
|
})
|
||||||
{
|
|
||||||
EventID: "evt-2",
|
secretRepo := &mockSecretRepo{secrets: make(map[string]string)}
|
||||||
Timestamp: now.Add(-time.Minute),
|
redisRepo := &devMockRedisRepo{data: make(map[string]string)}
|
||||||
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"}`,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
h := &DevHandler{
|
h := &DevHandler{
|
||||||
AuditRepo: auditRepo,
|
Hydra: &service.HydraAdminService{
|
||||||
Keto: new(MockKetoService),
|
AdminURL: "http://hydra.test",
|
||||||
|
HTTPClient: &http.Client{Transport: transport},
|
||||||
|
},
|
||||||
|
SecretRepo: secretRepo,
|
||||||
|
Redis: redisRepo,
|
||||||
|
Keto: new(devMockKetoService),
|
||||||
}
|
}
|
||||||
app := fiber.New()
|
app := fiber.New()
|
||||||
app.Use(func(c *fiber.Ctx) error {
|
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()
|
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)
|
resp, _ := app.Test(req, -1)
|
||||||
|
|
||||||
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
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
|
dbS, _ := secretRepo.GetByID(nil, "client-1")
|
||||||
_ = json.NewDecoder(resp.Body).Decode(&res)
|
assert.Equal(t, res.Client.ClientSecret, dbS)
|
||||||
assert.Len(t, res.Items, 1)
|
|
||||||
assert.Equal(t, "evt-1", res.Items[0].EventID)
|
|
||||||
assert.Equal(t, "success", res.Items[0].Status)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestListAuditLogs_NonAdminKetoErrorReturnsForbidden(t *testing.T) {
|
func TestGetStats_Success(t *testing.T) {
|
||||||
mockKeto := new(MockKetoService)
|
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
||||||
mockKeto.On("CheckPermission", mock.Anything, "user-1", "System", "AppManager", "member").Return(false, assert.AnError)
|
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{
|
h := &DevHandler{
|
||||||
AuditRepo: &mockAuditRepo{},
|
Hydra: &service.HydraAdminService{
|
||||||
|
AdminURL: "http://hydra.test",
|
||||||
|
HTTPClient: &http.Client{Transport: transport},
|
||||||
|
},
|
||||||
|
AuditRepo: auditRepo,
|
||||||
Keto: mockKeto,
|
Keto: mockKeto,
|
||||||
}
|
}
|
||||||
app := fiber.New()
|
app := fiber.New()
|
||||||
|
tenantID := "t1"
|
||||||
app.Use(func(c *fiber.Ctx) error {
|
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()
|
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)
|
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)
|
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)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|||||||
112
devfront/tests/devfront-audit.spec.ts
Normal file
112
devfront/tests/devfront-audit.spec.ts
Normal file
@@ -0,0 +1,112 @@
|
|||||||
|
import { expect, test } from "@playwright/test";
|
||||||
|
import {
|
||||||
|
type AuditLog,
|
||||||
|
type Consent,
|
||||||
|
installDevApiMock,
|
||||||
|
makeClient,
|
||||||
|
seedAuth,
|
||||||
|
} 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,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
121
devfront/tests/devfront-clients-lifecycle.spec.ts
Normal file
121
devfront/tests/devfront-clients-lifecycle.spec.ts
Normal file
@@ -0,0 +1,121 @@
|
|||||||
|
import { expect, test } from "@playwright/test";
|
||||||
|
import {
|
||||||
|
type ClientStatus,
|
||||||
|
type Consent,
|
||||||
|
installDevApiMock,
|
||||||
|
makeClient,
|
||||||
|
seedAuth,
|
||||||
|
} 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/);
|
||||||
|
});
|
||||||
|
});
|
||||||
45
devfront/tests/devfront-consents.spec.ts
Normal file
45
devfront/tests/devfront-consents.spec.ts
Normal file
@@ -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();
|
||||||
|
});
|
||||||
|
});
|
||||||
50
devfront/tests/devfront-security.spec.ts
Normal file
50
devfront/tests/devfront-security.spec.ts
Normal file
@@ -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();
|
||||||
|
});
|
||||||
|
});
|
||||||
371
devfront/tests/helpers/devfront-fixtures.ts
Normal file
371
devfront/tests/helpers/devfront-fixtures.ts
Normal file
@@ -0,0 +1,371 @@
|
|||||||
|
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<string, unknown>;
|
||||||
|
};
|
||||||
|
|
||||||
|
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<
|
||||||
|
string,
|
||||||
|
{ items: AuditLog[]; next_cursor?: string }
|
||||||
|
>;
|
||||||
|
auditLogs?: AuditLog[];
|
||||||
|
onUpdateStatus?: (status: ClientStatus) => void;
|
||||||
|
onRotateSecret?: (newSecret: string) => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function makeClient(
|
||||||
|
id: string,
|
||||||
|
overrides: Partial<Client> = {},
|
||||||
|
): 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<string, unknown>;
|
||||||
|
}) || { 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<string, unknown>;
|
||||||
|
}) || { 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);
|
||||||
|
});
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user