Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
sam-one: token and admin subcommands over the local admin API
Antonio Ojeae92a87f54cc9
diff --git a/cmd/sam-one/admin.go b/cmd/sam-one/admin.gonew file mode 100644index 00000000..06a73c35--- /dev/null+++ b/cmd/sam-one/admin.go@@ -0,0 +1,239 @@+// 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 main++import (+ "bytes"+ "encoding/json"+ "fmt"+ "io"+ "net/http"+ "os"+ "text/tabwriter"+ "time"++ "github.com/google/sam/api"+ "github.com/google/sam/internal/standalone"+ "github.com/google/sam/internal/storage"+ "github.com/spf13/cobra"+ "google.golang.org/protobuf/proto"+)++// adminClient talks to a running sam-one's admin API; subcommands never open+// the database from a second process.+type adminClient struct {+ client *http.Client+ server string+ token string+}++// resolveAdminToken picks the admin credential: explicit flag, then the+// SAM_ADMIN_TOKEN env, then the token persisted in data-dir by a previous run.+func resolveAdminToken(flagVal, dataDir string) (string, error) {+ if flagVal != "" {+ return flagVal, nil+ }+ if env := os.Getenv("SAM_ADMIN_TOKEN"); env != "" {+ return env, nil+ }+ tok, err := standalone.AdminTokenFromDataDir(dataDir)+ if err != nil {+ return "", fmt.Errorf("no admin token: pass --admin-token, set SAM_ADMIN_TOKEN, or point --data-dir at a sam-one data directory (%v)", err)+ }+ return tok, nil+}++func (c *adminClient) do(method, path, contentType string, body []byte) ([]byte, error) {+ req, err := http.NewRequest(method, c.server+path, bytes.NewReader(body))+ if err != nil {+ return nil, err+ }+ req.Header.Set("Authorization", "Bearer "+c.token)+ if contentType != "" {+ req.Header.Set("Content-Type", contentType)+ }+ resp, err := c.client.Do(req)+ if err != nil {+ return nil, err+ }+ defer func() { _ = resp.Body.Close() }()+ respBody, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))+ if err != nil {+ return nil, err+ }+ if resp.StatusCode < 200 || resp.StatusCode >= 300 {+ return nil, fmt.Errorf("%s %s: %s: %s", method, path, resp.Status, bytes.TrimSpace(respBody))+ }+ return respBody, nil+}++type createdToken struct {+ ID string `json:"id"`+ Token string `json:"token"`+ Role string `json:"role"`+ ExpiresAt string `json:"expires_at"`+}++func (c *adminClient) createToken(role string, ttlHours, maxUsages int, description string) (*createdToken, error) {+ payload, err := json.Marshal(map[string]any{+ "role": role,+ "ttl_hours": ttlHours,+ "max_usages": maxUsages,+ "description": description,+ })+ if err != nil {+ return nil, err+ }+ body, err := c.do(http.MethodPost, "/admin/bootstrap-tokens", "application/json", payload)+ if err != nil {+ return nil, err+ }+ var created createdToken+ if err := json.Unmarshal(body, &created); err != nil {+ return nil, fmt.Errorf("failed to decode response %q: %w", body, err)+ }+ return &created, nil+}++func (c *adminClient) listTokens() ([]storage.BootstrapToken, error) {+ body, err := c.do(http.MethodGet, "/admin/bootstrap-tokens", "", nil)+ if err != nil {+ return nil, err+ }+ var list []storage.BootstrapToken+ if err := json.Unmarshal(body, &list); err != nil {+ return nil, fmt.Errorf("failed to decode response %q: %w", body, err)+ }+ return list, nil+}++func (c *adminClient) banPeer(peerID string) error {+ payload, err := proto.Marshal(&api.TokenRevokeRequest{PeerId: peerID})+ if err != nil {+ return err+ }+ _, err = c.do(http.MethodPost, "/admin/revoke", "application/x-protobuf", payload)+ return err+}++// newAdminSubcommands wires the token and admin command trees onto root.+func newAdminSubcommands() []*cobra.Command {+ var (+ server string+ adminToken string+ dataDir string+ clientFactory = func() (*adminClient, error) {+ tok, err := resolveAdminToken(adminToken, dataDir)+ if err != nil {+ return nil, err+ }+ return &adminClient{+ client: &http.Client{Timeout: 10 * time.Second},+ server: server,+ token: tok,+ }, nil+ }+ )++ addSharedFlags := func(cmd *cobra.Command) {+ cmd.PersistentFlags().StringVar(&server, "server", "http://127.0.0.1:8080", "Base URL of the running sam-one server")+ cmd.PersistentFlags().StringVar(&adminToken, "admin-token", "", "Admin API bearer token (or env SAM_ADMIN_TOKEN, or read from --data-dir)")+ cmd.PersistentFlags().StringVar(&dataDir, "data-dir", ".", "sam-one data directory holding the persisted admin token")+ }++ var (+ role string+ ttlHours int+ maxUsages int+ description string+ )+ tokenCreate := &cobra.Command{+ Use: "create",+ Short: "Generate a new scoped bootstrap token",+ RunE: func(cmd *cobra.Command, args []string) error {+ c, err := clientFactory()+ if err != nil {+ return err+ }+ created, err := c.createToken(role, ttlHours, maxUsages, description)+ if err != nil {+ return err+ }+ cmd.Printf("Token: %s\n", created.Token)+ cmd.Printf("Role: %s\n", created.Role)+ cmd.Printf("Expires: %s\n", created.ExpiresAt)+ cmd.Println("The plain token is shown only once; store it now.")+ return nil+ },+ }+ tokenCreate.Flags().StringVar(&role, "role", api.RoleNode, "Role bound to the token")+ tokenCreate.Flags().IntVar(&ttlHours, "ttl-hours", 24, "Token validity in hours")+ tokenCreate.Flags().IntVar(&maxUsages, "max-usages", 1, "How many enrollments the token allows")+ tokenCreate.Flags().StringVar(&description, "description", "", "Free-form note stored with the token")++ tokenList := &cobra.Command{+ Use: "list",+ Short: "List active bootstrap tokens",+ RunE: func(cmd *cobra.Command, args []string) error {+ c, err := clientFactory()+ if err != nil {+ return err+ }+ list, err := c.listTokens()+ if err != nil {+ return err+ }+ tw := tabwriter.NewWriter(cmd.OutOrStdout(), 2, 4, 2, ' ', 0)+ _, _ = fmt.Fprintln(tw, "ID\tROLE\tUSAGES\tEXPIRES\tDESCRIPTION")+ for _, tok := range list {+ id := tok.ID+ if len(id) > 12 {+ id = id[:12]+ }+ _, _ = fmt.Fprintf(tw, "%s\t%s\t%d/%d\t%s\t%s\n",+ id, tok.Role, tok.UsagesCount, tok.MaxUsages,+ tok.ExpiresAt.Format(time.RFC3339), tok.Description)+ }+ return tw.Flush()+ },+ }++ tokenCmd := &cobra.Command{Use: "token", Short: "Manage bootstrap tokens on a running sam-one"}+ addSharedFlags(tokenCmd)+ tokenCmd.AddCommand(tokenCreate, tokenList)++ adminBan := &cobra.Command{+ Use: "ban <peer-id>",+ Short: "Ban a peer ID from the mesh",+ Args: cobra.ExactArgs(1),+ RunE: func(cmd *cobra.Command, args []string) error {+ c, err := clientFactory()+ if err != nil {+ return err+ }+ if err := c.banPeer(args[0]); err != nil {+ return err+ }+ cmd.Printf("Peer %s banned\n", args[0])+ return nil+ },+ }++ adminCmd := &cobra.Command{Use: "admin", Short: "Administrative actions on a running sam-one"}+ addSharedFlags(adminCmd)+ adminCmd.AddCommand(adminBan)++ return []*cobra.Command{tokenCmd, adminCmd}+}diff --git a/cmd/sam-one/admin_test.go b/cmd/sam-one/admin_test.gonew file mode 100644index 00000000..7d2b17ab--- /dev/null+++ b/cmd/sam-one/admin_test.go@@ -0,0 +1,139 @@+// 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 main++import (+ "encoding/json"+ "io"+ "net/http"+ "net/http/httptest"+ "os"+ "path/filepath"+ "strings"+ "testing"+ "time"++ "github.com/google/sam/api"+ "github.com/google/sam/internal/storage"+ "google.golang.org/protobuf/proto"+)++func newFakeAdminAPI(t *testing.T) *httptest.Server {+ t.Helper()+ mux := http.NewServeMux()+ mux.HandleFunc("/admin/bootstrap-tokens", func(w http.ResponseWriter, r *http.Request) {+ if r.Header.Get("Authorization") != "Bearer adm-tok" {+ http.Error(w, "Unauthorized", http.StatusUnauthorized)+ return+ }+ switch r.Method {+ case http.MethodPost:+ var req map[string]any+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {+ http.Error(w, "bad body", http.StatusBadRequest)+ return+ }+ w.WriteHeader(http.StatusCreated)+ _ = json.NewEncoder(w).Encode(map[string]any{+ "id": "abcdef123456",+ "token": "sam-bt-fresh",+ "role": req["role"],+ "expires_at": "2026-12-31T00:00:00Z",+ })+ case http.MethodGet:+ _ = json.NewEncoder(w).Encode([]storage.BootstrapToken{{+ ID: "abcdef123456",+ Role: api.RoleNode,+ MaxUsages: 3,+ UsagesCount: 1,+ Description: "seeded",+ ExpiresAt: time.Date(2026, 12, 31, 0, 0, 0, 0, time.UTC),+ }})+ default:+ http.Error(w, "method", http.StatusMethodNotAllowed)+ }+ })+ mux.HandleFunc("/admin/revoke", func(w http.ResponseWriter, r *http.Request) {+ if r.Header.Get("Authorization") != "Bearer adm-tok" {+ http.Error(w, "Unauthorized", http.StatusUnauthorized)+ return+ }+ body, _ := io.ReadAll(r.Body)+ var req api.TokenRevokeRequest+ if err := proto.Unmarshal(body, &req); err != nil || req.PeerId != "12D3KooTestPeer" {+ http.Error(w, "wrong peer", http.StatusBadRequest)+ return+ }+ _, _ = w.Write([]byte("ok"))+ })+ srv := httptest.NewServer(mux)+ t.Cleanup(srv.Close)+ return srv+}++func TestAdminClient(t *testing.T) {+ ts := newFakeAdminAPI(t)+ c := &adminClient{client: ts.Client(), server: ts.URL, token: "adm-tok"}++ created, err := c.createToken(api.RoleNode, 24, 1, "note")+ if err != nil {+ t.Fatalf("createToken failed: %v", err)+ }+ if created.Token != "sam-bt-fresh" || created.Role != api.RoleNode {+ t.Errorf("unexpected created token: %+v", created)+ }++ list, err := c.listTokens()+ if err != nil {+ t.Fatalf("listTokens failed: %v", err)+ }+ if len(list) != 1 || list[0].Description != "seeded" || list[0].UsagesCount != 1 {+ t.Errorf("unexpected token list: %+v", list)+ }++ if err := c.banPeer("12D3KooTestPeer"); err != nil {+ t.Fatalf("banPeer failed: %v", err)+ }++ bad := &adminClient{client: ts.Client(), server: ts.URL, token: "wrong"}+ if _, err := bad.listTokens(); err == nil || !strings.Contains(err.Error(), "401") {+ t.Errorf("expected 401 error with wrong token, got %v", err)+ }+}++func TestResolveAdminToken(t *testing.T) {+ dir := t.TempDir()+ if err := os.WriteFile(filepath.Join(dir, "admin-token"), []byte("sam_adm_file\n"), 0o600); err != nil {+ t.Fatalf("failed to write token file: %v", err)+ }++ t.Setenv("SAM_ADMIN_TOKEN", "")+ if got, err := resolveAdminToken("", dir); err != nil || got != "sam_adm_file" {+ t.Errorf("data-dir fallback = %q, %v; want sam_adm_file", got, err)+ }++ t.Setenv("SAM_ADMIN_TOKEN", "sam_adm_env")+ if got, err := resolveAdminToken("", dir); err != nil || got != "sam_adm_env" {+ t.Errorf("env precedence = %q, %v; want sam_adm_env", got, err)+ }+ if got, err := resolveAdminToken("sam_adm_flag", dir); err != nil || got != "sam_adm_flag" {+ t.Errorf("flag precedence = %q, %v; want sam_adm_flag", got, err)+ }++ t.Setenv("SAM_ADMIN_TOKEN", "")+ if _, err := resolveAdminToken("", t.TempDir()); err == nil {+ t.Error("expected an error when no admin token source exists")+ }+}diff --git a/cmd/sam-one/main.go b/cmd/sam-one/main.goindex 2a3d8fa0..b3c131d2 100644--- a/cmd/sam-one/main.go+++ b/cmd/sam-one/main.go@@ -124,6 +124,8 @@ func main() {rootCmd.Flags().StringVar(&allowedAudiencesFlag, "allowed-audiences", api.DefaultAudience, "Comma-separated list of allowed OIDC audiences")rootCmd.Flags().StringVar(&logLevel, "log-level", "", "Log level: debug, info, warn, error")+ rootCmd.AddCommand(newAdminSubcommands()...)+ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)defer cancel()diff --git a/internal/controlplane/server.go b/internal/controlplane/server.goindex e3c5c7be..6cd12c3a 100644--- a/internal/controlplane/server.go+++ b/internal/controlplane/server.go@@ -1440,12 +1440,25 @@ func (s *Server) checkAdminAuth(w http.ResponseWriter, r *http.Request) bool {return true}-// HandleAdminBootstrapTokens HTTP POST `/admin/bootstrap-tokens`+// HandleAdminBootstrapTokens HTTP POST/GET `/admin/bootstrap-tokens`func (s *Server) HandleAdminBootstrapTokens(w http.ResponseWriter, r *http.Request) {if !s.checkAdminAuth(w, r) {return}+ if r.Method == http.MethodGet {+ list, err := s.store.ListBootstrapTokens(r.Context())+ if err != nil {+ logger.Errorf("Failed to list bootstrap tokens: %v", err)+ http.Error(w, "Internal server error", http.StatusInternalServerError)+ return+ }+ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(http.StatusOK)+ _ = json.NewEncoder(w).Encode(list)+ return+ }+if r.Method != http.MethodPost {http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)returndiff --git a/internal/controlplane/server_test.go b/internal/controlplane/server_test.goindex 00bf21e4..97d22882 100644--- a/internal/controlplane/server_test.go+++ b/internal/controlplane/server_test.go@@ -1933,3 +1933,82 @@ func TestInitRegisterRoutesEmbedded(t *testing.T) {t.Fatalf("Close() without Start failed: %v", err)}}++// TestAdminBootstrapTokensList pins the admin listing surface used by+// `sam-one token list`: created tokens show up, and the list is admin-gated.+func TestAdminBootstrapTokensList(t *testing.T) {+ dbPath := filepath.Join(t.TempDir(), "cp-admin-tokens.db")+ store, err := storage.NewSQLStore("sqlite", dbPath)+ if err != nil {+ t.Fatalf("failed to create store: %v", err)+ }+ defer func() { _ = store.Close() }()++ srv, err := NewServer(Options{+ DriverName: "sqlite",+ DataSourceName: dbPath,+ AdminToken: "test-admin-token",+ AllowedAudiences: []string{"sam-mesh-audience"},+ }, store)+ if err != nil {+ t.Fatalf("failed to create server: %v", err)+ }++ mux := http.NewServeMux()+ srv.RegisterRoutes(mux)+ ts := httptest.NewServer(mux)+ defer ts.Close()+ client := &http.Client{Timeout: 5 * time.Second}++ // Create one token through the existing POST surface.+ req, err := http.NewRequest(http.MethodPost, ts.URL+"/admin/bootstrap-tokens",+ strings.NewReader(`{"role":"sam:role:node","ttl_hours":1,"max_usages":3,"description":"cli test"}`))+ if err != nil {+ t.Fatalf("failed to build request: %v", err)+ }+ req.Header.Set("Authorization", "Bearer test-admin-token")+ req.Header.Set("Content-Type", "application/json")+ resp, err := client.Do(req)+ if err != nil {+ t.Fatalf("POST /admin/bootstrap-tokens failed: %v", err)+ }+ _ = resp.Body.Close()+ if resp.StatusCode != http.StatusCreated {+ t.Fatalf("POST /admin/bootstrap-tokens status = %s, want 201", resp.Status)+ }++ // GET with the admin token returns it.+ req, err = http.NewRequest(http.MethodGet, ts.URL+"/admin/bootstrap-tokens", nil)+ if err != nil {+ t.Fatalf("failed to build request: %v", err)+ }+ req.Header.Set("Authorization", "Bearer test-admin-token")+ resp, err = client.Do(req)+ if err != nil {+ t.Fatalf("GET /admin/bootstrap-tokens failed: %v", err)+ }+ if resp.StatusCode != http.StatusOK {+ t.Fatalf("GET /admin/bootstrap-tokens status = %s, want 200", resp.Status)+ }+ var list []storage.BootstrapToken+ if err := json.NewDecoder(resp.Body).Decode(&list); err != nil {+ t.Fatalf("failed to decode token list: %v", err)+ }+ _ = resp.Body.Close()+ if len(list) != 1 {+ t.Fatalf("token list length = %d, want 1", len(list))+ }+ if list[0].Role != "sam:role:node" || list[0].MaxUsages != 3 || list[0].Description != "cli test" {+ t.Errorf("unexpected token record: %+v", list[0])+ }++ // GET without credentials is refused.+ resp, err = client.Get(ts.URL + "/admin/bootstrap-tokens")+ if err != nil {+ t.Fatalf("unauthenticated GET failed: %v", err)+ }+ _ = resp.Body.Close()+ if resp.StatusCode != http.StatusUnauthorized {+ t.Errorf("unauthenticated GET status = %s, want 401", resp.Status)+ }+}diff --git a/internal/standalone/standalone.go b/internal/standalone/standalone.goindex 95c13cda..8a291d13 100644--- a/internal/standalone/standalone.go+++ b/internal/standalone/standalone.go@@ -407,6 +407,21 @@ func generateToken(prefix string) (string, error) {return prefix + hex.EncodeToString(b), nil}+// AdminTokenFromDataDir reads the admin token a previous run persisted in+// dataDir, so CLI subcommands can authenticate without re-supplying it.+func AdminTokenFromDataDir(dataDir string) (string, error) {+ path := filepath.Join(dataDir, adminTokenFile)+ data, err := os.ReadFile(path)+ if err != nil {+ return "", err+ }+ tok := strings.TrimSpace(string(data))+ if tok == "" {+ return "", fmt.Errorf("token file %s is empty", path)+ }+ return tok, nil+}+// loadOrCreateTokenFile reuses the token persisted at path, generating and// saving a fresh one (0600) on first boot.func loadOrCreateTokenFile(path, prefix string) (string, error) {