Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
feat: node self-reported service catalog + console Services view
Fernando Marino95ba2aacb68c
diff --git a/internal/console/public/app.js b/internal/console/public/app.jsindex 91864650..2a3b6208 100644--- a/internal/console/public/app.js+++ b/internal/console/public/app.js@@ -244,6 +244,7 @@ async function loadData() {setTableMessage('table-enrollments', 4, 'Restricted to administrators.');}renderNodesTable(data.enrolled_nodes || []);+ renderServicesTable(data.node_catalog || {});renderRoutersTable(data.active_routers || []);renderRouterTopography(data.active_routers || []);renderBootstrapTokensTable(data.bootstrap_tokens || []);@@ -353,6 +354,39 @@ function renderNodesTable(nodes) {`).join('');}+// Service type is a protobuf enum (SERVICE_TYPE_MCP = 1, SERVICE_TYPE_INFERENCE = 2,+// SERVICE_TYPE_A2A = 3); plain encoding/json on the Go side emits the bare+// int, not the enum name, and omits it entirely (omitempty) if it's ever 0.+const SERVICE_TYPE_NAMES = { 1: 'mcp', 2: 'inference', 3: 'a2a' };++function renderServicesTable(nodeCatalog) {+ const tbody = document.getElementById('table-services');+ const peerIDs = Object.keys(nodeCatalog || {});+ const rows = [];+ for (const peerID of peerIDs) {+ const entry = nodeCatalog[peerID] || {};+ const services = entry.services || [];+ for (const svc of services) {+ rows.push({ peerID, reportedAt: entry.reported_at, svc });+ }+ }++ if (rows.length === 0) {+ tbody.innerHTML = `<tr><td colspan="5" class="text-center">No nodes have reported any services yet</td></tr>`;+ return;+ }++ tbody.innerHTML = rows.map(({ peerID, reportedAt, svc }) => `+ <tr>+ <td>${escapeHTML(svc.name || '')}</td>+ <td>${escapeHTML(SERVICE_TYPE_NAMES[svc.type] || 'unknown')}</td>+ <td>${escapeHTML(svc.description || '')}</td>+ <td><code>${escapeHTML(peerID)}</code></td>+ <td>${escapeHTML(reportedAt || '')}</td>+ </tr>+ `).join('');+}+function getStatusBadge(status) {if (status === 0 || status === 'ENROLLMENT_STATUS_PENDING') {return `<span class="badge badge-pending">Pending</span>`;diff --git a/internal/console/public/index.html b/internal/console/public/index.htmlindex 5a6f6bfd..ec55b739 100644--- a/internal/console/public/index.html+++ b/internal/console/public/index.html@@ -71,6 +71,10 @@<svg aria-hidden="true" viewBox="0 0 24 24" width="20" height="20" stroke="currentColor" stroke-width="2" fill="none"><circle cx="12" cy="12" r="10"></circle><line x1="12" y1="16" x2="12" y2="12"></line><line x1="12" y1="8" x2="12.01" y2="8"></line></svg>Nodes</a>+ <a href="#services" class="nav-item" data-target="services">+ <svg aria-hidden="true" viewBox="0 0 24 24" width="20" height="20" stroke="currentColor" stroke-width="2" fill="none"><rect x="2" y="3" width="20" height="14" rx="2" ry="2"></rect><line x1="8" y1="21" x2="16" y2="21"></line><line x1="12" y1="17" x2="12" y2="21"></line></svg>+ Services+ </a><a href="#enrollments" class="nav-item" data-target="enrollments"><svg aria-hidden="true" viewBox="0 0 24 24" width="20" height="20" stroke="currentColor" stroke-width="2" fill="none"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"></path><polyline points="22 4 12 14.01 9 11.01"></polyline></svg>Enrollments@@ -199,6 +203,32 @@</div></section>+ <!-- Services View: self-reported by each node (see /nodes/catalog);+ a live-status cache, not authoritative, so ReportedAt matters. -->+ <section id="view-services" class="view-section">+ <div class="section-header">+ <h2>Mesh Services</h2>+ </div>+ <div class="card">+ <div class="table-responsive">+ <table class="data-table">+ <thead>+ <tr>+ <th>Service</th>+ <th>Type</th>+ <th>Description</th>+ <th>Node ID</th>+ <th>Reported At</th>+ </tr>+ </thead>+ <tbody id="table-services">+ <tr><td colspan="5" class="text-center">Loading...</td></tr>+ </tbody>+ </table>+ </div>+ </div>+ </section>+<!-- Enrollments View --><section id="view-enrollments" class="view-section"><div class="section-header">diff --git a/internal/controlplane/catalog.go b/internal/controlplane/catalog.gonew file mode 100644index 00000000..e92d289d--- /dev/null+++ b/internal/controlplane/catalog.go@@ -0,0 +1,131 @@+// Copyright 2026 Google LLC+//+// Licensed 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 controlplane++import (+ "crypto/ed25519"+ "encoding/base64"+ "encoding/json"+ "io"+ "net/http"+ "strings"+ "time"++ "github.com/google/sam/api"+ "github.com/google/sam/internal/identity"+)++// nodeCatalogEntry is what HandleNodeCatalog caches per reporting peer.+type nodeCatalogEntry struct {+ Services []*api.ServiceInfo `json:"services"`+ ReportedAt time.Time `json:"reported_at"`+}++// nodeCatalogRequest is HandleNodeCatalog's request body. The reporting+// peer's identity comes from its verified Biscuit, never from this body -+// a node can only ever report on itself.+type nodeCatalogRequest struct {+ Services []*api.ServiceInfo `json:"services"`+}++// catalogSnapshot returns a stable copy of the current node service catalog+// cache, safe to range over or marshal without holding catalogMu.+func (s *Server) catalogSnapshot() map[string]nodeCatalogEntry {+ s.catalogMu.RLock()+ defer s.catalogMu.RUnlock()+ snap := make(map[string]nodeCatalogEntry, len(s.catalog))+ for k, v := range s.catalog {+ snap[k] = v+ }+ return snap+}++// HandleNodeCatalog HTTP POST /nodes/catalog - a node self-reports the+// services it currently has registered locally (the same data+// list_local_services already answers on the node itself), so the control+// plane can show mesh-wide service topology without needing to be a DHT+// participant or open a P2P connection to every enrolled node itself.+//+// This is a live-status cache, not authoritative state: a node that goes+// offline without ever reporting an empty catalog just leaves its last+// report in place until ReportedAt visibly goes stale. Good enough for an+// admin-facing "what's running where" view; not a substitute for the real+// per-request Biscuit authorization every actual service call still goes+// through independently.+func (s *Server) HandleNodeCatalog(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodPost {+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)+ return+ }++ authHeader := r.Header.Get("Authorization")+ if !strings.HasPrefix(authHeader, "Bearer ") {+ http.Error(w, "Missing node Biscuit token in Authorization header", http.StatusUnauthorized)+ return+ }+ biscuitBytes, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(authHeader, "Bearer "))+ if err != nil {+ http.Error(w, "Malformed base64 token", http.StatusBadRequest)+ return+ }++ ctx := r.Context()+ validKeys, err := s.store.GetAllValidKeys(ctx)+ if err != nil {+ logger.Errorf("Failed to retrieve valid signing keys: %v", err)+ http.Error(w, "Internal server error", http.StatusInternalServerError)+ return+ }+ var trustedKeys []ed25519.PublicKey+ for _, k := range validKeys {+ trustedKeys = append(trustedKeys, k.Public)+ }++ peerID, err := identity.VerifyAndExtractPeerID(trustedKeys, biscuitBytes, s.config.BiscuitTimeout)+ if err != nil {+ logger.Warnw("Invalid biscuit presented to /nodes/catalog", "error", err)+ http.Error(w, "Invalid biscuit: "+err.Error(), http.StatusUnauthorized)+ return+ }++ nodeRecord, err := s.store.GetNode(ctx, peerID.String())+ if err != nil || nodeRecord == nil || nodeRecord.CheckAdmission(time.Now()) != nil {+ http.Error(w, "Node not enrolled or not admitted", http.StatusUnauthorized)+ return+ }++ r.Body = http.MaxBytesReader(w, r.Body, maxRequestBodyBytes)+ body, err := io.ReadAll(r.Body)+ if err != nil {+ http.Error(w, "Failed to read body", http.StatusBadRequest)+ return+ }+ defer func() { _ = r.Body.Close() }()++ var req nodeCatalogRequest+ if err := json.Unmarshal(body, &req); err != nil {+ http.Error(w, "Invalid JSON body", http.StatusBadRequest)+ return+ }++ s.catalogMu.Lock()+ s.catalog[peerID.String()] = nodeCatalogEntry{+ Services: req.Services,+ ReportedAt: time.Now(),+ }+ s.catalogMu.Unlock()++ w.WriteHeader(http.StatusNoContent)+}diff --git a/internal/controlplane/server.go b/internal/controlplane/server.goindex 5f398ba9..c771df5f 100644--- a/internal/controlplane/server.go+++ b/internal/controlplane/server.go@@ -77,6 +77,13 @@ type Server struct {providersMu sync.RWMutexproviders map[string]*oidc.Provider+ // catalogMu/catalog cache each node's self-reported local service list+ // (see HandleNodeCatalog), keyed by peer ID. In-memory only: this is a+ // live-status view, not authoritative state, so it's fine to lose on+ // restart - every node re-reports on its own next periodic push.+ catalogMu sync.RWMutex+ catalog map[string]nodeCatalogEntry+ctx context.Contextcancel context.CancelFuncwg sync.WaitGroup@@ -98,6 +105,7 @@ func NewServer(config Options, store storage.Store) (*Server, error) {mesh: NewNopMeshAdapter(),limiter: rate.NewLimiter(rate.Limit(EnrollRateLimit), EnrollBurst),providers: make(map[string]*oidc.Provider),+ catalog: make(map[string]nodeCatalogEntry),ctx: ctx,cancel: cancel,}, nil@@ -204,6 +212,7 @@ func (s *Server) RegisterRoutes(mux *http.ServeMux) {mux.HandleFunc("/enroll", s.HandleEnroll)mux.HandleFunc("/enroll/status", s.HandleEnrollStatus)mux.HandleFunc("/refresh", s.HandleRefresh)+ mux.HandleFunc("/nodes/catalog", s.HandleNodeCatalog)mux.HandleFunc("/admin/bootstrap-tokens", s.HandleAdminBootstrapTokens)mux.HandleFunc("/admin/enrollments", s.HandleAdminEnrollments)mux.HandleFunc("/admin/enrollments/", s.HandleAdminEnrollmentAction)diff --git a/internal/controlplane/ui.go b/internal/controlplane/ui.goindex cb688fcb..32b9dd49 100644--- a/internal/controlplane/ui.go+++ b/internal/controlplane/ui.go@@ -86,6 +86,7 @@ func (s *Server) HandleAdminStatus(w http.ResponseWriter, r *http.Request) {"enrollment_requests": reqs,"bootstrap_tokens": tokens,"policy_json": policyJSON,+ "node_catalog": s.catalogSnapshot(),}w.Header().Set("Content-Type", "application/json")diff --git a/internal/node/controlplane.go b/internal/node/controlplane.goindex de40ed4a..9e8ce145 100644--- a/internal/node/controlplane.go+++ b/internal/node/controlplane.go@@ -19,6 +19,7 @@ import ("context""crypto/ed25519""encoding/base64"+ "encoding/json""fmt""io""net/http"@@ -251,3 +252,48 @@ func FetchMeshPolicy(ctx context.Context, controlPlaneURL string, biscuitToken [return &policyResp, nil}++// nodeCatalogRequest mirrors internal/controlplane/catalog.go's request+// body - kept as a plain JSON struct here rather than a shared package+// import, matching how this file already treats /policies as a boundary+// between the two components.+type nodeCatalogRequest struct {+ Services []*api.ServiceInfo `json:"services"`+}++// ReportNodeCatalog self-reports this node's locally registered services to+// the control plane's /nodes/catalog endpoint, so an admin can see mesh-wide+// service topology (see catalog.go's HandleNodeCatalog for why this exists+// instead of the control plane discovering it via DHT/P2P itself).+func ReportNodeCatalog(ctx context.Context, controlPlaneURL string, biscuitToken []byte, services []*api.ServiceInfo) error {+ if !strings.HasPrefix(controlPlaneURL, "http://") && !strings.HasPrefix(controlPlaneURL, "https://") {+ controlPlaneURL = "https://" + controlPlaneURL+ }+ controlPlaneURL = strings.TrimSuffix(controlPlaneURL, "/")++ payload, err := json.Marshal(nodeCatalogRequest{Services: services})+ if err != nil {+ return fmt.Errorf("failed to encode catalog report: %w", err)+ }++ urlStr := controlPlaneURL + "/nodes/catalog"+ req, err := http.NewRequestWithContext(ctx, "POST", urlStr, bytes.NewReader(payload))+ if err != nil {+ return fmt.Errorf("failed to create HTTP request: %w", err)+ }+ req.Header.Set("Content-Type", "application/json")+ req.Header.Set("Authorization", "Bearer "+base64.StdEncoding.EncodeToString(biscuitToken))++ client := &http.Client{Timeout: 10 * time.Second}+ resp, err := client.Do(req)+ if err != nil {+ return fmt.Errorf("HTTP request failed: %w", err)+ }+ defer resp.Body.Close() //nolint:errcheck++ if resp.StatusCode != http.StatusNoContent {+ body, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))+ return fmt.Errorf("control plane returned status %s: %s", resp.Status, string(body))+ }+ return nil+}diff --git a/internal/node/node.go b/internal/node/node.goindex cf934824..82343746 100644--- a/internal/node/node.go+++ b/internal/node/node.go@@ -631,6 +631,10 @@ func (n *SamNode) Start(ctx context.Context) error {// Periodically sync mesh policyn.startPolicySyncLoop(ctx, n.config.PolicySyncInterval)+ // Periodically self-report local services to the control plane, so an+ // admin can see mesh-wide service topology.+ n.startCatalogReportLoop(ctx, n.config.CatalogReportInterval)+return nil}@@ -2208,6 +2212,60 @@ func (n *SamNode) syncMeshPolicy(ctx context.Context) error {return nil}+// reportNodeCatalog self-reports this node's local service list to the+// control plane (see internal/controlplane/catalog.go's HandleNodeCatalog),+// so an admin console can show mesh-wide service topology.+func (n *SamNode) reportNodeCatalog(ctx context.Context) error {+ controlPlaneURL, err := n.Store.LoadControlPlaneURL()+ if err != nil || controlPlaneURL == "" {+ return fmt.Errorf("control plane URL not found in store")+ }++ token := n.GetIdentity()+ if len(token) == 0 {+ return fmt.Errorf("node has no identity token to report its catalog")+ }++ services := n.ListLocalServices(api.ServiceType_SERVICE_TYPE_UNSPECIFIED)+ if err := ReportNodeCatalog(ctx, controlPlaneURL, token, services); err != nil {+ return fmt.Errorf("failed to report node catalog: %w", err)+ }+ return nil+}++func (n *SamNode) startCatalogReportLoop(ctx context.Context, interval time.Duration) {+ if interval <= 0 {+ interval = 1 * time.Minute+ }++ go func() {+ // Run an initial report after a short delay, once services have had+ // a chance to register at startup.+ select {+ case <-ctx.Done():+ return+ case <-time.After(5 * time.Second):+ if err := n.reportNodeCatalog(ctx); err != nil {+ logger.Warnf("Initial node catalog report failed: %v", err)+ }+ }++ ticker := time.NewTicker(interval)+ defer ticker.Stop()++ for {+ select {+ case <-ctx.Done():+ return+ case <-ticker.C:+ if err := n.reportNodeCatalog(ctx); err != nil {+ logger.Warnf("Periodic node catalog report failed: %v", err)+ }+ }+ }+ }()+}+func (n *SamNode) startPolicySyncLoop(ctx context.Context, interval time.Duration) {if interval <= 0 {interval = 1 * time.Hourdiff --git a/internal/node/options.go b/internal/node/options.goindex 730ecd1e..7c4c7cc1 100644--- a/internal/node/options.go+++ b/internal/node/options.go@@ -86,6 +86,12 @@ type Options struct {// is tight enough that even simple interpreted-language MCP servers can// miss it on first spawn.BackendProbeTimeout time.Duration+ // CatalogReportInterval specifies how often the node self-reports its+ // locally registered services to the control plane (POST+ // /nodes/catalog), so an admin can see mesh-wide service topology+ // without the control plane needing DHT/P2P access to every node+ // itself. Zero uses the default.+ CatalogReportInterval time.Duration}// Default applies default values to Options if they are not specified.@@ -136,6 +142,9 @@ func (o *Options) Default() {if o.PolicySyncInterval == 0 {o.PolicySyncInterval = 1 * time.Hour}+ if o.CatalogReportInterval == 0 {+ o.CatalogReportInterval = 1 * time.Minute+ }if o.PolicySyncJitter <= 0 {o.PolicySyncJitter = 10 * time.Second}