|
| 1 | +// Copyright 2026 Google LLC |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +package node |
| 16 | + |
| 17 | +import ( |
| 18 | + "context" |
| 19 | + "encoding/json" |
| 20 | + "fmt" |
| 21 | + "net/http" |
| 22 | + "time" |
| 23 | + |
| 24 | + "github.com/libp2p/go-libp2p/core/peer" |
| 25 | + "github.com/multiformats/go-multiaddr" |
| 26 | +) |
| 27 | + |
| 28 | +// newDebugHandler serves the operator diagnostics under /debug. These were MCP |
| 29 | +// tools once; they moved here so agents never see them in their tool list (#318). |
| 30 | +func newDebugHandler(n *SamNode) http.Handler { |
| 31 | + mux := http.NewServeMux() |
| 32 | + mux.HandleFunc("GET /debug/mesh-info", func(w http.ResponseWriter, r *http.Request) { |
| 33 | + info, err := n.meshInfo() |
| 34 | + if err != nil { |
| 35 | + http.Error(w, err.Error(), http.StatusInternalServerError) |
| 36 | + return |
| 37 | + } |
| 38 | + writeDebugJSON(w, info) |
| 39 | + }) |
| 40 | + mux.HandleFunc("GET /debug/connectivity", func(w http.ResponseWriter, r *http.Request) { |
| 41 | + writeDebugJSON(w, n.connectivityStats(r.Context(), r.URL.Query().Get("peer_id"))) |
| 42 | + }) |
| 43 | + mux.HandleFunc("GET /debug/network-info", func(w http.ResponseWriter, r *http.Request) { |
| 44 | + writeDebugJSON(w, n.networkInfo()) |
| 45 | + }) |
| 46 | + mux.HandleFunc("GET /debug/token-info", func(w http.ResponseWriter, r *http.Request) { |
| 47 | + writeDebugJSON(w, n.tokenInfo()) |
| 48 | + }) |
| 49 | + mux.HandleFunc("GET /debug/logs", func(w http.ResponseWriter, r *http.Request) { |
| 50 | + writeDebugJSON(w, map[string]any{"logs": GetRecentLogs()}) |
| 51 | + }) |
| 52 | + mux.HandleFunc("POST /debug/connect-peer", func(w http.ResponseWriter, r *http.Request) { |
| 53 | + var req struct { |
| 54 | + PeerAddr string `json:"peer_addr"` |
| 55 | + } |
| 56 | + r.Body = http.MaxBytesReader(w, r.Body, maxRequestBodyBytes) |
| 57 | + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { |
| 58 | + http.Error(w, "Invalid request body", http.StatusBadRequest) |
| 59 | + return |
| 60 | + } |
| 61 | + if req.PeerAddr == "" { |
| 62 | + http.Error(w, "peer_addr is required", http.StatusBadRequest) |
| 63 | + return |
| 64 | + } |
| 65 | + if err := n.connectPeer(r.Context(), req.PeerAddr); err != nil { |
| 66 | + http.Error(w, fmt.Sprintf("Failed to connect: %v", err), http.StatusInternalServerError) |
| 67 | + return |
| 68 | + } |
| 69 | + writeDebugJSON(w, map[string]string{"status": "connected"}) |
| 70 | + }) |
| 71 | + return mux |
| 72 | +} |
| 73 | + |
| 74 | +func writeDebugJSON(w http.ResponseWriter, v any) { |
| 75 | + w.Header().Set("Content-Type", "application/json") |
| 76 | + if err := json.NewEncoder(w).Encode(v); err != nil { |
| 77 | + logger.Errorf("Failed to encode response: %v", err) |
| 78 | + } |
| 79 | +} |
| 80 | + |
| 81 | +// meshInfo backs both the get_mesh_info MCP tool and GET /debug/mesh-info. |
| 82 | +func (n *SamNode) meshInfo() (map[string]any, error) { |
| 83 | + if n == nil { |
| 84 | + return nil, fmt.Errorf("node not initialized") |
| 85 | + } |
| 86 | + |
| 87 | + peers := n.Host.Network().Peers() |
| 88 | + var connectedPeers []string |
| 89 | + for _, p := range peers { |
| 90 | + connectedPeers = append(connectedPeers, p.String()) |
| 91 | + } |
| 92 | + dhtSize := n.DHT.RoutingTable().Size() |
| 93 | + |
| 94 | + resData := map[string]any{ |
| 95 | + "peer_id": n.Host.ID().String(), |
| 96 | + "connected_peers": connectedPeers, |
| 97 | + "dht_size": dhtSize, |
| 98 | + "router_peer_id": n.RouterPeerID.String(), |
| 99 | + } |
| 100 | + if n.BoundSocketPath != "" { |
| 101 | + resData["local_api_socket"] = n.BoundSocketPath |
| 102 | + } |
| 103 | + return resData, nil |
| 104 | +} |
| 105 | + |
| 106 | +// connectivityStats backs GET /debug/connectivity: with a peer ID it pings that |
| 107 | +// peer, otherwise it pings the SAM router. |
| 108 | +func (n *SamNode) connectivityStats(ctx context.Context, peerIDStr string) map[string]any { |
| 109 | + stats := map[string]any{ |
| 110 | + "connected_peers": len(n.Host.Network().Peers()), |
| 111 | + "total_known_peers": len(n.Host.Peerstore().Peers()), |
| 112 | + } |
| 113 | + |
| 114 | + if peerIDStr != "" { |
| 115 | + pid, err := peer.Decode(peerIDStr) |
| 116 | + if err == nil { |
| 117 | + n.preparePeerAddrs(ctx, pid) |
| 118 | + start := time.Now() |
| 119 | + err := n.Host.Connect(ctx, peer.AddrInfo{ID: pid}) |
| 120 | + stats["ping_latency_ms"] = time.Since(start).Milliseconds() |
| 121 | + stats["ping_error"] = err != nil |
| 122 | + if err != nil { |
| 123 | + stats["ping_error_msg"] = err.Error() |
| 124 | + } |
| 125 | + } else { |
| 126 | + stats["ping_error"] = true |
| 127 | + stats["ping_error_msg"] = "invalid peer id" |
| 128 | + } |
| 129 | + } else if n.RouterPeerID != "" { |
| 130 | + start := time.Now() |
| 131 | + err := n.Host.Connect(ctx, peer.AddrInfo{ID: n.RouterPeerID}) |
| 132 | + stats["router_latency_ms"] = time.Since(start).Milliseconds() |
| 133 | + stats["router_error"] = err != nil |
| 134 | + if err != nil { |
| 135 | + stats["router_error_msg"] = err.Error() |
| 136 | + } |
| 137 | + } |
| 138 | + |
| 139 | + return stats |
| 140 | +} |
| 141 | + |
| 142 | +// tokenInfo backs GET /debug/token-info. |
| 143 | +func (n *SamNode) tokenInfo() map[string]any { |
| 144 | + info := map[string]any{ |
| 145 | + "has_token": false, |
| 146 | + } |
| 147 | + |
| 148 | + token, err := n.Store.LoadIdentity() |
| 149 | + if err == nil && len(token) > 0 { |
| 150 | + info["has_token"] = true |
| 151 | + exp, err := n.Store.LoadIdentityExpiration() |
| 152 | + if err == nil { |
| 153 | + info["expires_in_seconds"] = time.Until(time.Unix(exp, 0)).Seconds() |
| 154 | + info["is_expired"] = time.Now().Unix() > exp |
| 155 | + } |
| 156 | + } |
| 157 | + return info |
| 158 | +} |
| 159 | + |
| 160 | +// networkInfo backs GET /debug/network-info. |
| 161 | +func (n *SamNode) networkInfo() map[string]any { |
| 162 | + listenAddrs := []string{} |
| 163 | + for _, a := range n.Host.Network().ListenAddresses() { |
| 164 | + listenAddrs = append(listenAddrs, a.String()) |
| 165 | + } |
| 166 | + |
| 167 | + observedAddrs := []string{} |
| 168 | + for _, a := range n.Host.Addrs() { |
| 169 | + observedAddrs = append(observedAddrs, a.String()) |
| 170 | + } |
| 171 | + |
| 172 | + return map[string]any{ |
| 173 | + "listen_addresses": listenAddrs, |
| 174 | + "observed_addresses": observedAddrs, |
| 175 | + } |
| 176 | +} |
| 177 | + |
| 178 | +// connectPeer backs POST /debug/connect-peer. |
| 179 | +func (n *SamNode) connectPeer(ctx context.Context, peerAddr string) error { |
| 180 | + ma, err := multiaddr.NewMultiaddr(peerAddr) |
| 181 | + if err != nil { |
| 182 | + return err |
| 183 | + } |
| 184 | + addrInfo, err := peer.AddrInfoFromP2pAddr(ma) |
| 185 | + if err != nil { |
| 186 | + return err |
| 187 | + } |
| 188 | + if n.revokedPeers != nil && n.revokedPeers.Contains(addrInfo.ID.String()) { |
| 189 | + return fmt.Errorf("failed to dial: failed to dial %s: gater disallows connection to peer", addrInfo.ID) |
| 190 | + } |
| 191 | + if n.Store.IsBanned(addrInfo.ID) { |
| 192 | + return fmt.Errorf("failed to dial: failed to dial %s: gater disallows connection to peer", addrInfo.ID) |
| 193 | + } |
| 194 | + conns := n.Host.Network().ConnsToPeer(addrInfo.ID) |
| 195 | + connectedness := n.Host.Network().Connectedness(addrInfo.ID) |
| 196 | + logger.Debugf("[connect-peer] Target peer %s, connectedness: %v, active conns: %d", addrInfo.ID, connectedness, len(conns)) |
| 197 | + |
| 198 | + err = n.Host.Connect(ctx, *addrInfo) |
| 199 | + logger.Debugf("[connect-peer] Host.Connect returned error: %v", err) |
| 200 | + return err |
| 201 | +} |
0 commit comments