Copilot commented on code in PR #1623:
URL: https://github.com/apache/dubbo-admin/pull/1623#discussion_r4438214020


##########
pkg/core/discovery/subscriber/zk_metadata.go:
##########
@@ -105,10 +113,76 @@ func (z *ZKMetadataEventSubscriber) 
processUpsert(metadataRes *meshresource.ZKMe
                return 
processMetadataUpsert[*meshresource.ServiceConsumerMetadataResource](
                        metadataRes, 
meshresource.ToServiceConsumerMetadataByRawData, z.storeRouter, z.emitter)
        }
+       if app, revision, ok := 
applicationMetadataPath(metadataRes.Spec.NodePath); ok {
+               resource, err := 
meshresource.ParseRPCInstanceMetadata(metadataRes.Mesh, app, revision, 
metadataRes.Spec.NodeData)
+               if err != nil {
+                       return err
+               }
+               return z.upsertApplicationMetadata(resource)
+       }
        logger.Warnf("unknown metadata, node path: %s, node data: %s", 
metadataRes.Spec.NodePath, metadataRes.Spec.NodeData)
        return nil
 }
 
+func applicationMetadataPath(path string) (string, string, bool) {
+       parts := strings.Split(path, constants.PathSeparator)
+       if len(parts) != 5 || parts[1] != "dubbo" || parts[2] != "metadata" ||
+               parts[3] == "" || parts[4] == "" {
+               return "", "", false
+       }
+       return parts[3], parts[4], true
+}
+
+func (z *ZKMetadataEventSubscriber) upsertApplicationMetadata(resource 
*meshresource.RPCInstanceMetadataResource) error {
+       st, err := 
z.storeRouter.ResourceKindRoute(meshresource.RPCInstanceMetadataKind)
+       if err != nil {
+               return err
+       }
+       old, exists, err := st.GetByKey(resource.ResourceKey())
+       if err != nil {
+               return err
+       }
+       if !exists {
+               if err := st.Add(resource); err != nil {
+                       return err
+               }
+               z.emitter.Send(events.NewResourceChangedEvent(cache.Added, nil, 
resource))
+               return nil
+       }
+       if err := st.Update(resource); err != nil {
+               return err
+       }
+       z.emitter.Send(events.NewResourceChangedEvent(cache.Updated, 
old.(coremodel.Resource), resource))
+       return nil
+}
+
+func (z *ZKMetadataEventSubscriber) processApplicationMetadataDelete(resource 
*meshresource.ZKMetadataResource) error {
+       if resource.Spec == nil {
+               return nil
+       }
+       key := zkInterfaceRegistration(resource.Mesh, resource.Spec.NodePath)
+       if key == nil {
+               app, revision, ok := 
applicationMetadataPath(resource.Spec.NodePath)
+               if !ok {
+                       return nil
+               }

Review Comment:
   Provider-contract metadata deletes are still ignored here: a 
`/dubbo/metadata/.../provider/...` path matches neither 
`zkInterfaceRegistration` nor `applicationMetadataPath`, so its derived 
`ServiceProviderMetadataResource` remains stored. The runtime hashes those 
derived resources, meaning deleting the last ZooKeeper definition can leave the 
old contract callable instead of invalidating it as required by #1580. Handle 
provider-definition deletion as well, using the old metadata or a 
source-to-derived-key mapping to remove the matching resource and emit its 
delete event.



##########
pkg/mcp/availability/index.go:
##########
@@ -0,0 +1,320 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package availability
+
+import (
+       "sort"
+       "strings"
+       "sync"
+       "time"
+
+       meshproto "github.com/apache/dubbo-admin/api/mesh/v1alpha1"
+       "github.com/apache/dubbo-admin/pkg/core/discovery"
+       meshresource 
"github.com/apache/dubbo-admin/pkg/core/resource/apis/mesh/v1alpha1"
+)
+
+type State string
+
+const (
+       Active   State = "ACTIVE"
+       Inactive State = "INACTIVE"
+       Unknown  State = "UNKNOWN"
+)
+
+type Identity struct {
+       Mesh        string
+       ServiceName string
+       Group       string
+       Version     string
+}
+
+type SyncState = discovery.SyncState
+
+type Evidence struct {
+       Complete  bool
+       Available bool
+       Protocols []string
+}
+
+type Result struct {
+       Identity      Identity
+       Protocol      string
+       State         State
+       InactiveSince time.Time
+       Evidence      Evidence
+}
+
+type Snapshot struct {
+       // Identities includes published bindings even after their discovery 
Resources disappear.
+       Identities []Identity
+       Services   []*meshresource.ServiceResource
+       Providers  []*meshresource.ServiceProviderMetadataResource
+       Instances  []*meshresource.RPCInstanceResource
+       Metadata   []*meshresource.RPCInstanceMetadataResource
+       Sync       SyncState
+       Now        time.Time
+}
+
+type LiveServiceIndex struct {
+       grace time.Duration
+       mu    sync.Mutex
+       items map[string]Result
+}
+
+func NewLiveServiceIndex(grace time.Duration) *LiveServiceIndex {
+       if grace <= 0 {
+               grace = 60 * time.Second
+       }
+       return &LiveServiceIndex{grace: grace, items: make(map[string]Result)}
+}
+
+func (i *LiveServiceIndex) Refresh(snapshot Snapshot) []Result {
+       now := snapshot.Now
+       if now.IsZero() {
+               now = time.Now()
+       }
+       identities := make(map[Identity]struct{})
+       for _, identity := range snapshot.Identities {
+               identities[identity] = struct{}{}
+       }
+       for _, service := range snapshot.Services {
+               if service != nil && service.Spec != nil {
+                       identities[Identity{
+                               Mesh: service.Mesh, ServiceName: 
service.Spec.Name,
+                               Group: service.Spec.Group, Version: 
service.Spec.Version,
+                       }] = struct{}{}
+               }
+       }
+       for _, provider := range snapshot.Providers {
+               if provider != nil && provider.Spec != nil {
+                       identities[Identity{
+                               Mesh: provider.Mesh, ServiceName: 
provider.Spec.ServiceName,
+                               Group: provider.Spec.Group, Version: 
provider.Spec.Version,
+                       }] = struct{}{}
+               }
+       }
+
+       i.mu.Lock()
+       defer i.mu.Unlock()
+       for _, previous := range i.items {
+               identities[previous.Identity] = struct{}{}

Review Comment:
   `Handler` shares this index across meshes, but `ReadSnapshot` supplies only 
the addressed mesh's resources and sync state. Adding every previous identity 
here re-evaluates other meshes against that partial snapshot. For example, an 
unhealthy mesh-B request changes an already-INACTIVE mesh-A entry to UNKNOWN; 
the next mesh-A request restarts its grace period, keeping a continuously down 
tool listed beyond 60 seconds. Partition the index by mesh, or refresh only the 
addressed mesh while preserving other meshes' entries.



##########
pkg/console/handler/mcp.go:
##########
@@ -0,0 +1,274 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package handler
+
+import (
+       "errors"
+       "net/http"
+       "strings"
+
+       "github.com/gin-contrib/sessions"
+       "github.com/gin-gonic/gin"
+
+       "github.com/apache/dubbo-admin/pkg/common/bizerror"
+       consolectx "github.com/apache/dubbo-admin/pkg/console/context"
+       "github.com/apache/dubbo-admin/pkg/console/model"
+       "github.com/apache/dubbo-admin/pkg/console/service"
+       "github.com/apache/dubbo-admin/pkg/console/util"
+       "github.com/apache/dubbo-admin/pkg/core/logger"
+       "github.com/apache/dubbo-admin/pkg/core/store"
+)
+
+func RequireMCPMesh() gin.HandlerFunc {
+       return func(c *gin.Context) {
+               if strings.TrimSpace(c.Query("mesh")) == "" {
+                       c.AbortWithStatusJSON(http.StatusBadRequest,
+                               
model.NewBizErrorResp(bizerror.New(bizerror.InvalidArgument, "mesh is 
required")))
+               }
+       }
+}
+
+func ListMCPServers(ctx consolectx.Context) gin.HandlerFunc {
+       return func(c *gin.Context) {
+               servers, err := service.ListMCPServers(ctx, c.Query("mesh"))
+               if err != nil {
+                       util.HandleServiceError(c, err)
+                       return
+               }
+               c.JSON(http.StatusOK, model.NewSuccessResp(servers))
+       }
+}
+
+func CreateMCPServer(ctx consolectx.Context) gin.HandlerFunc {
+       return func(c *gin.Context) {
+               req := new(model.MCPServerCreateReq)
+               if err := c.ShouldBindJSON(req); err != nil {
+                       util.HandleArgumentError(c, err)
+                       return
+               }
+               server, err := service.CreateMCPServer(ctx, req)
+               if err != nil {
+                       writeMCPResult(c, nil, err)
+                       return
+               }
+               auditMCPMutation(c, "server.create", req.Mesh, req.Name)
+               c.JSON(http.StatusOK, model.NewSuccessResp(server))
+       }
+}
+
+func GetMCPServer(ctx consolectx.Context) gin.HandlerFunc {
+       return func(c *gin.Context) {
+               server, err := service.GetMCPServerInMesh(ctx, c.Query("mesh"), 
c.Param("serverId"))
+               if err != nil {
+                       util.HandleServiceError(c, err)
+                       return
+               }
+               c.JSON(http.StatusOK, model.NewSuccessResp(server))
+       }
+}
+
+func DeleteMCPServer(ctx consolectx.Context) gin.HandlerFunc {
+       return func(c *gin.Context) {
+               err := service.DeleteMCPServer(ctx, c.Query("mesh"), 
c.Param("serverId"), c.Query("expectedResourceVersion"))
+               if err == nil {
+                       auditMCPMutation(c, "server.delete", c.Query("mesh"), 
c.Param("serverId"))
+               }
+               writeMCPResult(c, true, err)
+       }
+}
+
+func ReplaceMCPDraft(ctx consolectx.Context) gin.HandlerFunc {
+       return func(c *gin.Context) {
+               req := new(model.MCPDraftReq)
+               if err := c.ShouldBindJSON(req); err != nil {
+                       util.HandleArgumentError(c, err)
+                       return
+               }
+               server, err := service.ReplaceMCPDraft(ctx, c.Query("mesh"), 
c.Param("serverId"), req)
+               if err == nil {
+                       auditMCPMutation(c, "draft.replace", c.Query("mesh"), 
c.Param("serverId"))
+               }
+               writeMCPResult(c, server, err)
+       }
+}
+
+func ValidateMCPServer(ctx consolectx.Context) gin.HandlerFunc {
+       return func(c *gin.Context) {
+               result, err := service.ValidateMCPServer(ctx, c.Query("mesh"), 
c.Param("serverId"))
+               if err != nil {
+                       util.HandleServiceError(c, err)
+                       return
+               }
+               c.JSON(http.StatusOK, model.NewSuccessResp(result))
+       }
+}
+
+func CreateMCPTool(ctx consolectx.Context) gin.HandlerFunc {
+       return func(c *gin.Context) {
+               req := new(model.MCPToolReq)
+               if err := c.ShouldBindJSON(req); err != nil {
+                       util.HandleArgumentError(c, err)
+                       return
+               }
+               server, tool, err := service.CreateMCPTool(ctx, 
c.Query("mesh"), c.Param("serverId"), req)
+               if err != nil {
+                       writeMCPResult(c, nil, err)
+                       return
+               }
+               auditMCPMutation(c, "tool.create", c.Query("mesh"), 
c.Param("serverId"))
+               c.JSON(http.StatusOK, 
model.NewSuccessResp(map[string]any{"server": server, "tool": tool}))
+       }
+}
+
+func ListMCPTools(ctx consolectx.Context) gin.HandlerFunc {
+       return func(c *gin.Context) {
+               server, err := service.GetMCPServerInMesh(ctx, c.Query("mesh"), 
c.Param("serverId"))
+               if err != nil {
+                       util.HandleServiceError(c, err)
+                       return
+               }
+               if server.Spec == nil || server.Spec.Draft == nil {
+                       c.JSON(http.StatusOK, model.NewSuccessResp([]any{}))
+                       return
+               }
+               c.JSON(http.StatusOK, 
model.NewSuccessResp(server.Spec.Draft.Tools))
+       }
+}
+
+func GetMCPTool(ctx consolectx.Context) gin.HandlerFunc {
+       return func(c *gin.Context) {
+               tool, err := service.GetMCPTool(ctx, c.Query("mesh"), 
c.Param("serverId"), c.Param("toolId"))
+               if err != nil {
+                       util.HandleServiceError(c, err)
+                       return
+               }
+               c.JSON(http.StatusOK, model.NewSuccessResp(tool))
+       }
+}
+
+func ValidateMCPTool(ctx consolectx.Context) gin.HandlerFunc {
+       return func(c *gin.Context) {
+               result, err := service.ValidateMCPTool(ctx, c.Query("mesh"), 
c.Param("serverId"), c.Param("toolId"))
+               if err != nil {
+                       util.HandleServiceError(c, err)
+                       return
+               }
+               c.JSON(http.StatusOK, model.NewSuccessResp(result))
+       }
+}
+
+func ListMCPCredentials(ctx consolectx.Context) gin.HandlerFunc {
+       return func(c *gin.Context) {
+               credentials, err := service.ListMCPCredentials(ctx, 
c.Query("mesh"), c.Param("serverId"))
+               if err != nil {
+                       util.HandleServiceError(c, err)
+                       return
+               }
+               c.JSON(http.StatusOK, model.NewSuccessResp(credentials))
+       }
+}
+
+func CreateMCPCredential(ctx consolectx.Context) gin.HandlerFunc {
+       return func(c *gin.Context) {
+               req := new(model.MCPCredentialCreateReq)
+               if err := c.ShouldBindJSON(req); err != nil {
+                       util.HandleArgumentError(c, err)
+                       return
+               }
+               credential, err := service.CreateMCPCredential(ctx, 
c.Query("mesh"), c.Param("serverId"), req)
+               if err != nil {
+                       util.HandleServiceError(c, err)
+                       return
+               }
+               auditMCPMutation(c, "credential.create", c.Query("mesh"), 
c.Param("serverId"))
+               c.JSON(http.StatusOK, model.NewSuccessResp(credential))
+       }
+}
+
+func RevokeMCPCredential(ctx consolectx.Context) gin.HandlerFunc {
+       return func(c *gin.Context) {
+               credential, err := service.RevokeMCPCredential(ctx, 
c.Query("mesh"), c.Param("serverId"), c.Param("credentialId"), 
c.Query("expectedResourceVersion"))
+               if err == nil {
+                       auditMCPMutation(c, "credential.revoke", 
c.Query("mesh"), c.Param("serverId"))
+               }
+               writeMCPResult(c, credential, err)
+       }
+}
+
+func UpdateMCPTool(ctx consolectx.Context) gin.HandlerFunc {
+       return func(c *gin.Context) {
+               req := new(model.MCPToolReq)
+               if err := c.ShouldBindJSON(req); err != nil {
+                       util.HandleArgumentError(c, err)
+                       return
+               }
+               server, tool, err := service.UpdateMCPTool(ctx, 
c.Query("mesh"), c.Param("serverId"), c.Param("toolId"), req)
+               if err != nil {
+                       writeMCPResult(c, nil, err)
+                       return
+               }
+               auditMCPMutation(c, "tool.update", c.Query("mesh"), 
c.Param("serverId"))
+               c.JSON(http.StatusOK, 
model.NewSuccessResp(map[string]any{"server": server, "tool": tool}))
+       }
+}
+
+func DeleteMCPTool(ctx consolectx.Context) gin.HandlerFunc {
+       return func(c *gin.Context) {
+               server, err := service.DeleteMCPTool(ctx, c.Query("mesh"), 
c.Param("serverId"), c.Param("toolId"), c.Query("expectedResourceVersion"))
+               if err == nil {
+                       auditMCPMutation(c, "tool.delete", c.Query("mesh"), 
c.Param("serverId"))
+               }
+               writeMCPResult(c, server, err)
+       }
+}
+
+func PublishMCPServer(ctx consolectx.Context) gin.HandlerFunc {
+       return func(c *gin.Context) {
+               req := new(model.MCPPublishReq)
+               if err := c.ShouldBindJSON(req); err != nil {
+                       util.HandleArgumentError(c, err)
+                       return
+               }
+               server, err := service.PublishMCPServer(ctx, c.Query("mesh"), 
c.Param("serverId"), req)
+               if err == nil {
+                       auditMCPMutation(c, "server.publish", c.Query("mesh"), 
c.Param("serverId"))
+               }
+               writeMCPResult(c, server, err)
+       }
+}
+
+func writeMCPResult(c *gin.Context, value any, err error) {
+       if err == nil {
+               c.JSON(http.StatusOK, model.NewSuccessResp(value))
+               return
+       }
+       if errors.Is(err, store.ErrorResourceConflict("", "", "")) {
+               c.JSON(http.StatusConflict, model.NewErrorResp(err.Error()))
+               return
+       }
+       util.HandleServiceError(c, err)
+}
+
+func auditMCPMutation(c *gin.Context, action, mesh, serverID string) {
+       logger.Sugar().Infow("MCP control-plane mutation",
+               "action", action,
+               "principal", sessions.Default(c).Get("user"),

Review Comment:
   Current password and OAuth logins call `console/auth.PutPrincipal`, which 
stores `principal` and explicitly deletes the legacy `user` session key. 
Consequently, successful MCP mutations by newly logged-in users are audited 
with a null principal, including credential issuance and revocation. Read the 
authenticated principal through `consoleauth.PrincipalFromContext` (or 
`PrincipalFromSession`) and log its subject instead of the legacy key.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to