diff --git a/backend/internal/handler/dev_handler.go b/backend/internal/handler/dev_handler.go index 8ae2306b..710341e1 100644 --- a/backend/internal/handler/dev_handler.go +++ b/backend/internal/handler/dev_handler.go @@ -1958,7 +1958,8 @@ func (h *DevHandler) UpdateClient(c *fiber.Ctx) error { return errorJSON(c, fiber.StatusForbidden, "forbidden") } - if !h.canOperateClientByPermit(c, profile, currentSummary, "edit_config") { + isSuperAdmin := role == domain.RoleSuperAdmin + if !isSuperAdmin && !h.canOperateClientByPermit(c, profile, currentSummary, "edit_config") { return errorJSON(c, fiber.StatusForbidden, "forbidden: edit_config permission is required") } @@ -1971,7 +1972,7 @@ func (h *DevHandler) UpdateClient(c *fiber.Ctx) error { } // [Security] Check permission for private clients (both current and new type) - if currentSummary.Type == "private" || clientType == "private" { + if !isSuperAdmin && (currentSummary.Type == "private" || clientType == "private") { if !h.canBypassPrivateClientRestriction(c, profile, currentSummary, "edit_config") { return errorJSON(c, fiber.StatusForbidden, "forbidden: insufficient permissions for private client") } @@ -2072,19 +2073,48 @@ func (h *DevHandler) UpdateClient(c *fiber.Ctx) error { } tenantPolicyChanged := tenantAccessPolicyChanged(current.Metadata, updated.Metadata) + beforeScopes := strings.Fields(current.Scope) + afterScopes := strings.Fields(updated.Scope) + beforeAllowedTenants := readStringSliceMetadata(current.Metadata, "allowed_tenants") + afterAllowedTenants := readStringSliceMetadata(metadata, "allowed_tenants") + beforeIDTokenClaims := readMetadataValueOrNil(current.Metadata, "id_token_claims") + afterIDTokenClaims := readMetadataValueOrNil(metadata, "id_token_claims") + h.setAuditDetailsExtra(c, map[string]any{ "action": "UPDATE_CLIENT", "target_id": clientID, "tenant_id": tenantID, "before": map[string]any{ - "name": currentSummary.Name, - "type": currentSummary.Type, - "status": currentSummary.Status, + "name": currentSummary.Name, + "type": currentSummary.Type, + "status": currentSummary.Status, + "scopes": beforeScopes, + "tenant_access_restricted": readMetadataBoolValue(current.Metadata, "tenant_access_restricted"), + "allowed_tenants": beforeAllowedTenants, + "id_token_claims": beforeIDTokenClaims, + "token_endpoint_auth_method": current.TokenEndpointAuthMethod, + "jwks_uri": current.JWKSUri, + "backchannel_logout_uri": strings.TrimSpace(current.BackchannelLogoutURI()), + "backchannel_logout_session_required": current.BackchannelLogoutSessionRequiredValue(), + "headless_login_enabled": readMetadataBoolValue(current.Metadata, domain.MetadataHeadlessLoginEnabled), + "headless_token_endpoint_auth_method": readMetadataStringValue(current.Metadata, domain.MetadataHeadlessTokenEndpointAuthMethod), + "headless_jwks_uri": readMetadataStringValue(current.Metadata, domain.MetadataHeadlessJWKSURI), }, "after": map[string]any{ - "name": strings.TrimSpace(updated.ClientName), - "type": clientTypeOrDefault(updated.TokenEndpointAuthMethod), - "status": resolveStatusFromMetadata(updated.Metadata), + "name": strings.TrimSpace(updated.ClientName), + "type": clientTypeOrDefault(updated.TokenEndpointAuthMethod), + "status": resolveStatusFromMetadata(updated.Metadata), + "scopes": afterScopes, + "tenant_access_restricted": readMetadataBoolValue(metadata, "tenant_access_restricted"), + "allowed_tenants": afterAllowedTenants, + "id_token_claims": afterIDTokenClaims, + "token_endpoint_auth_method": resolvedTokenAuthMethod, + "jwks_uri": resolvedJWKSURI, + "backchannel_logout_uri": strings.TrimSpace(resolvedBackchannelLogoutURI), + "backchannel_logout_session_required": resolvedBackchannelLogoutSessionRequired, + "headless_login_enabled": readMetadataBoolValue(metadata, domain.MetadataHeadlessLoginEnabled), + "headless_token_endpoint_auth_method": readMetadataStringValue(metadata, domain.MetadataHeadlessTokenEndpointAuthMethod), + "headless_jwks_uri": readMetadataStringValue(metadata, domain.MetadataHeadlessJWKSURI), }, }) @@ -2934,6 +2964,49 @@ func readMetadataBoolValue(metadata map[string]interface{}, key string) bool { return value } +func readStringSliceMetadata(metadata map[string]interface{}, key string) []string { + if metadata == nil { + return nil + } + raw, ok := metadata[key] + if !ok || raw == nil { + return nil + } + switch typed := raw.(type) { + case []string: + result := make([]string, 0, len(typed)) + for _, item := range typed { + if trimmed := strings.TrimSpace(item); trimmed != "" { + result = append(result, trimmed) + } + } + return result + case []interface{}: + result := make([]string, 0, len(typed)) + for _, item := range typed { + if str, ok := item.(string); ok { + if trimmed := strings.TrimSpace(str); trimmed != "" { + result = append(result, trimmed) + } + } + } + return result + default: + return nil + } +} + +func readMetadataValueOrNil(metadata map[string]interface{}, key string) interface{} { + if metadata == nil { + return nil + } + value, ok := metadata[key] + if !ok { + return nil + } + return value +} + func normalizeBackchannelLogoutMetadata(metadata map[string]interface{}, logoutURI string, sessionRequired bool) (map[string]interface{}, error) { if metadata == nil { metadata = map[string]interface{}{} diff --git a/backend/internal/handler/dev_handler_test.go b/backend/internal/handler/dev_handler_test.go index 9f9cc291..11faa6e6 100644 --- a/backend/internal/handler/dev_handler_test.go +++ b/backend/internal/handler/dev_handler_test.go @@ -2,6 +2,7 @@ package handler import ( "baron-sso-backend/internal/domain" + auditmw "baron-sso-backend/internal/middleware" "baron-sso-backend/internal/service" "bytes" "context" @@ -591,6 +592,199 @@ func TestUpdateClient_ManagedRPAdminRequiresEditConfigPermission(t *testing.T) { mockKeto.AssertExpectations(t) } +func TestUpdateClient_SuperAdminBypassesEditConfigPermission(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]any{ + "client_id": "client-1", + "client_name": "App One", + "redirect_uris": []string{ + "http://localhost/cb", + }, + "grant_types": []string{"authorization_code", "refresh_token"}, + "response_types": []string{"code"}, + "scope": "openid profile email offline_access", + "token_endpoint_auth_method": "client_secret_basic", + "metadata": map[string]any{ + "status": "active", + "tenant_id": "tenant-1", + }, + }), nil + } + if r.Method == http.MethodPut && r.URL.Path == "/clients/client-1" { + return httpJSONAny(r, http.StatusOK, map[string]any{ + "client_id": "client-1", + "client_name": "App One Updated", + "redirect_uris": []string{ + "http://localhost/cb", + }, + "grant_types": []string{"authorization_code", "refresh_token"}, + "response_types": []string{"code"}, + "scope": "openid profile email offline_access", + "token_endpoint_auth_method": "client_secret_basic", + "metadata": map[string]any{ + "status": "active", + "tenant_id": "tenant-1", + }, + }), nil + } + return httpJSONAny(r, http.StatusNotFound, nil), nil + }) + + h := &DevHandler{ + Hydra: &service.HydraAdminService{ + AdminURL: "http://hydra.test", + HTTPClient: &http.Client{Transport: transport}, + }, + } + + app := fiber.New() + tenantID := "tenant-1" + app.Use(func(c *fiber.Ctx) error { + c.Locals("user_profile", &domain.UserProfileResponse{ + ID: "user-1", + Role: domain.RoleSuperAdmin, + TenantID: &tenantID, + }) + return c.Next() + }) + app.Put("/api/v1/dev/clients/:id", h.UpdateClient) + + body, _ := json.Marshal(map[string]any{ + "name": "App One Updated", + }) + req := httptest.NewRequest(http.MethodPut, "/api/v1/dev/clients/client-1", bytes.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + + resp, _ := app.Test(req, -1) + assert.Equal(t, http.StatusOK, resp.StatusCode) + + var result clientDetailResponse + _ = json.NewDecoder(resp.Body).Decode(&result) + assert.Equal(t, "App One Updated", result.Client.Name) +} + +func TestUpdateClient_AuditDetailsIncludeGeneralSettingChanges(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]any{ + "client_id": "client-1", + "client_name": "App One", + "redirect_uris": []string{ + "http://localhost/cb", + }, + "grant_types": []string{"authorization_code", "refresh_token"}, + "response_types": []string{"code"}, + "scope": "openid profile email", + "token_endpoint_auth_method": "client_secret_basic", + "metadata": map[string]any{ + "status": "active", + "tenant_id": "tenant-1", + "tenant_access_restricted": false, + "allowed_tenants": []any{}, + "id_token_claims": []any{}, + "headless_login_enabled": false, + "headless_jwks_uri": "", + "headless_token_endpoint_auth_method": "", + }, + }), nil + } + if r.Method == http.MethodPut && r.URL.Path == "/clients/client-1" { + return httpJSONAny(r, http.StatusOK, map[string]any{ + "client_id": "client-1", + "client_name": "App One Updated", + "redirect_uris": []string{ + "http://localhost/cb", + }, + "grant_types": []string{"authorization_code", "refresh_token"}, + "response_types": []string{"code"}, + "scope": "openid profile email tenant", + "token_endpoint_auth_method": "private_key_jwt", + "metadata": map[string]any{ + "status": "active", + "tenant_id": "tenant-1", + "tenant_access_restricted": true, + "allowed_tenants": []any{"tenant-1", "tenant-2"}, + "id_token_claims": []any{map[string]any{"namespace": "top_level", "key": "locale", "valueType": "text", "value": "ko-KR"}}, + "headless_login_enabled": true, + "headless_jwks_uri": "https://rp.example.com/jwks.json", + "headless_token_endpoint_auth_method": "private_key_jwt", + }, + }), nil + } + return httpJSONAny(r, http.StatusNotFound, nil), nil + }) + + auditRepo := &mockAuditRepo{} + h := &DevHandler{ + Hydra: &service.HydraAdminService{ + AdminURL: "http://hydra.test", + HTTPClient: &http.Client{Transport: transport}, + }, + AuditRepo: auditRepo, + } + + app := fiber.New() + app.Use(auditmw.AuditMiddleware(auditmw.AuditConfig{Repo: auditRepo})) + tenantID := "tenant-1" + app.Use(func(c *fiber.Ctx) error { + c.Locals("user_profile", &domain.UserProfileResponse{ + ID: "user-1", + Role: domain.RoleSuperAdmin, + TenantID: &tenantID, + }) + return c.Next() + }) + app.Put("/api/v1/dev/clients/:id", h.UpdateClient) + + body, _ := json.Marshal(map[string]any{ + "name": "App One Updated", + "scopes": []string{"openid", "profile", "email", "tenant"}, + "metadata": map[string]any{ + "tenant_access_restricted": true, + "allowed_tenants": []string{"tenant-1", "tenant-2"}, + "id_token_claims": []map[string]any{ + { + "namespace": "top_level", + "key": "locale", + "valueType": "text", + "value": "ko-KR", + }, + }, + "headless_login_enabled": true, + "headless_jwks_uri": "https://rp.example.com/jwks.json", + "headless_token_endpoint_auth_method": "private_key_jwt", + "backchannel_logout_uri": "https://rp.example.com/logout", + "backchannel_logout_session_required": true, + }, + "tokenEndpointAuthMethod": "private_key_jwt", + "jwksUri": "https://rp.example.com/jwks.json", + "backchannelLogoutUri": "https://rp.example.com/logout", + "backchannelLogoutSessionRequired": true, + }) + req := httptest.NewRequest(http.MethodPut, "/api/v1/dev/clients/client-1", bytes.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + + resp, _ := app.Test(req, -1) + assert.Equal(t, http.StatusOK, resp.StatusCode) + if assert.NotEmpty(t, auditRepo.logs) { + var details map[string]any + assert.NoError(t, json.Unmarshal([]byte(auditRepo.logs[0].Details), &details)) + before, _ := details["before"].(map[string]any) + after, _ := details["after"].(map[string]any) + assert.NotNil(t, before) + assert.NotNil(t, after) + assert.Contains(t, after, "scopes") + assert.Contains(t, after, "tenant_access_restricted") + assert.Contains(t, after, "allowed_tenants") + assert.Contains(t, after, "id_token_claims") + assert.Contains(t, after, "headless_login_enabled") + assert.Contains(t, after, "headless_jwks_uri") + assert.Contains(t, after, "backchannel_logout_uri") + assert.Contains(t, after, "backchannel_logout_session_required") + } +} + func TestListClients_ProtectedSystemClientHidden(t *testing.T) { transport := roundTripFunc(func(r *http.Request) (*http.Response, error) { if r.URL.Path == "/clients" { diff --git a/devfront/src/features/clients/ClientGeneralPage.tsx b/devfront/src/features/clients/ClientGeneralPage.tsx index 984d0382..7db96bce 100644 --- a/devfront/src/features/clients/ClientGeneralPage.tsx +++ b/devfront/src/features/clients/ClientGeneralPage.tsx @@ -54,6 +54,7 @@ import { import { t } from "../../lib/i18n"; import { resolveProfileRole } from "../../lib/role"; import { cn } from "../../lib/utils"; +import { fetchMe, type UserProfile } from "../auth/authApi"; import { ClientDetailTabs } from "./ClientDetailTabs"; interface ScopeItem { @@ -326,12 +327,19 @@ function ClientGeneralPage() { const params = useParams(); const navigate = useNavigate(); const queryClient = useQueryClient(); + const hasAccessToken = Boolean(auth.user?.access_token); const clientId = params.id; const isCreate = !clientId; - const currentUserId = auth.user?.profile.sub; const systemRole = resolveProfileRole( auth.user?.profile as Record | undefined, ); + const { data: me } = useQuery({ + queryKey: ["userMe"], + queryFn: fetchMe, + enabled: hasAccessToken, + }); + const currentUserId = me?.id ?? auth.user?.profile.sub; + const effectiveSystemRole = me?.role?.trim() || systemRole; const { data, isLoading, error } = useQuery({ queryKey: ["client", clientId], queryFn: () => fetchClient(clientId as string), @@ -569,7 +577,7 @@ function ClientGeneralPage() { const securityProfile: SecurityProfile = clientType === "pkce" ? "pkce" : "private"; const canEditExistingClientGeneralSettings = - systemRole === "super_admin" || + effectiveSystemRole === "super_admin" || relationData?.items?.some( (item: ClientRelation) => item.subject === `User:${currentUserId}` &&