Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
console: make bootstrap token ownership explicit and copyable
Antonio Ojea4e1e7594f17f
diff --git a/cmd/sam-console/public/app.js b/cmd/sam-console/public/app.jsindex b954d8cf..ef1a0e8d 100644--- a/cmd/sam-console/public/app.js+++ b/cmd/sam-console/public/app.js@@ -360,13 +360,11 @@ function updateUIForRole(role, userId) {if (ownerInput) {const group = ownerInput.closest('.input-group');if (group) {- if (role === 'admin') {- group.style.display = 'flex';- ownerInput.required = true;- } else {- group.style.display = 'none';- ownerInput.required = false;- ownerInput.value = userId; // Scoped to user implicitly+ // Only admins may set an owner; for everyone else the server infers it+ // from the session, so the field is hidden and left empty.+ group.style.display = role === 'admin' ? 'flex' : 'none';+ if (role !== 'admin') {+ ownerInput.value = '';}}}@@ -467,23 +465,26 @@ function renderBootstrapTokensTable(tokens) {window.generateBootstrapToken = async function() {const role = document.getElementById('token-role').value;- const owner_id = document.getElementById('token-owner').value;+ const owner_id = document.getElementById('token-owner').value.trim();const max_usages = parseInt(document.getElementById('token-usages').value, 10);const ttl_hours = parseInt(document.getElementById('token-ttl').value, 10) || 24;const description = document.getElementById('token-desc').value;const payload = {role,- owner_id,max_usages,ttl_hours,description};+ // Omitted entirely so the server falls back to the authenticated session.+ if (owner_id) {+ payload.owner_id = owner_id;+ }try {const res = await actionRequest('api/user/bootstrap-tokens', 'POST', payload);if (res && res.token) {- alert('Bootstrap Token Generated Successfully!\n\nToken: ' + res.token + '\n\nCopy this token now. It will not be shown again.');+ showGeneratedToken(res);document.getElementById('form-generate-token').reset();loadData();}@@ -492,6 +493,36 @@ window.generateBootstrapToken = async function() {}};+function showGeneratedToken(res) {+ const panel = document.getElementById('token-result');+ const input = document.getElementById('token-result-value');+ input.value = res.token;+ document.getElementById('token-result-owner').textContent = res.owner_id || 'you';+ document.getElementById('token-result-cmd').textContent =+ 'sam-node join --bootstrap-token ' + res.token + ' <control-plane-url>';+ panel.hidden = false;+ input.focus();+ input.select();+}++window.copyGeneratedToken = async function() {+ const input = document.getElementById('token-result-value');+ const btn = document.getElementById('token-copy-btn');+ input.select();+ try {+ // Only available on secure origins; execCommand covers plain-HTTP deployments.+ if (navigator.clipboard && window.isSecureContext) {+ await navigator.clipboard.writeText(input.value);+ } else if (!document.execCommand('copy')) {+ throw new Error('copy command rejected');+ }+ btn.textContent = 'Copied';+ } catch (err) {+ btn.textContent = 'Press Ctrl+C';+ }+ setTimeout(() => { btn.textContent = 'Copy'; }, 2000);+};+function writeVarint(value) {const bytes = [];while (value > 127) {diff --git a/cmd/sam-console/public/index.html b/cmd/sam-console/public/index.htmlindex 162e9615..e77b9e5f 100644--- a/cmd/sam-console/public/index.html+++ b/cmd/sam-console/public/index.html@@ -262,8 +262,9 @@</select></div><div class="input-group" style="display: flex; flex-direction: column; gap: 4px;">- <label for="token-owner" style="font-size: 0.85rem; color: var(--text-secondary);">Owner ID</label>- <input type="text" id="token-owner" placeholder="e.g. system:serviceaccount:sam-kind:node-a-sa" style="background: rgba(0,0,0,0.2); border: 1px solid var(--border-color); color: var(--text-primary); border-radius: 4px; padding: 8px;" required>+ <label for="token-owner" style="font-size: 0.85rem; color: var(--text-secondary);">Owner ID <span style="opacity: 0.7;">(optional)</span></label>+ <input type="text" id="token-owner" placeholder="Leave blank to use your own identity" style="background: rgba(0,0,0,0.2); border: 1px solid var(--border-color); color: var(--text-primary); border-radius: 4px; padding: 8px;">+ <small id="token-owner-hint" style="font-size: 0.75rem; color: var(--text-secondary); opacity: 0.8;">Admins only: issue this token on behalf of another user. The user must have logged in at least once.</small></div><div class="input-group" style="display: flex; flex-direction: column; gap: 4px;"><label for="token-usages" style="font-size: 0.85rem; color: var(--text-secondary);">Max Usages</label>@@ -279,6 +280,19 @@</div><button type="submit" class="btn btn-primary" style="margin-top: 12px; max-width: 200px;">Generate Token</button></form>+ <div id="token-result" hidden style="margin-top: 1.5rem; max-width: 500px; border: 1px solid var(--border-color); border-radius: 6px; padding: 1rem; background: rgba(0,0,0,0.2);">+ <div style="font-size: 0.85rem; color: var(--text-secondary); margin-bottom: 8px;">+ Token generated for owner <code id="token-result-owner"></code>. Copy it now — it is not stored and will not be shown again.+ </div>+ <div style="display: flex; gap: 8px; align-items: center;">+ <input type="text" id="token-result-value" readonly onfocus="this.select();"+ style="flex: 1; font-family: monospace; background: rgba(0,0,0,0.35); border: 1px solid var(--border-color); color: var(--text-primary); border-radius: 4px; padding: 8px;">+ <button type="button" class="btn" id="token-copy-btn" onclick="copyGeneratedToken();">Copy</button>+ </div>+ <div style="font-size: 0.75rem; color: var(--text-secondary); margin-top: 8px;">+ Join a node with: <code id="token-result-cmd"></code>+ </div>+ </div></div><div class="card"><h3>Active Tokens</h3>diff --git a/internal/controlplane/server.go b/internal/controlplane/server.goindex 770f9ffe..2af3583d 100644--- a/internal/controlplane/server.go+++ b/internal/controlplane/server.go@@ -1210,6 +1210,7 @@ func (s *Server) HandleEnroll(w http.ResponseWriter, r *http.Request) {PublicKey: req.PublicKey,Biscuit: biscuitBytes,Role: tokenRecord.Role,+ OwnerID: tokenRecord.OwnerID,EnrollmentType: "BOOTSTRAP",Labels: req.Labels,EnrolledAt: time.Now(),@@ -1557,6 +1558,7 @@ func (s *Server) HandleAdminEnrollmentAction(w http.ResponseWriter, r *http.RequPublicKey: enrollReq.PublicKey,Biscuit: biscuitBytes,Role: tokenRecord.Role,+ OwnerID: tokenRecord.OwnerID,EnrollmentType: "BOOTSTRAP",Labels: enrollReq.Labels,EnrolledAt: time.Now(),@@ -1796,6 +1798,7 @@ func (s *Server) HandleUserBootstrapTokens(w http.ResponseWriter, r *http.Requesvar req struct {Role string `json:"role"`+ OwnerID string `json:"owner_id"`TTLHours int `json:"ttl_hours"`MaxUsages int `json:"max_usages"`Description string `json:"description"`@@ -1817,6 +1820,12 @@ func (s *Server) HandleUserBootstrapTokens(w http.ResponseWriter, r *http.Requesreturn}+ ownerID, status, err := s.resolveTokenOwner(r.Context(), user, req.OwnerID)+ if err != nil {+ http.Error(w, err.Error(), status)+ return+ }+if req.TTLHours <= 0 {req.TTLHours = 24}@@ -1836,7 +1845,7 @@ func (s *Server) HandleUserBootstrapTokens(w http.ResponseWriter, r *http.RequesID: tokenID,TokenHash: tokenID,Role: req.Role,- OwnerID: user.ID,+ OwnerID: ownerID,MaxUsages: req.MaxUsages,UsagesCount: 0,Description: req.Description,@@ -1856,10 +1865,31 @@ func (s *Server) HandleUserBootstrapTokens(w http.ResponseWriter, r *http.Reques"id": tokenRecord.ID,"token": tokenVal,"role": tokenRecord.Role,+ "owner_id": tokenRecord.OwnerID,"expires_at": tokenRecord.ExpiresAt.Format(time.RFC3339),})}+// resolveTokenOwner determines which user a bootstrap token is issued on behalf of.+// The owner defaults to the caller; only admins may override it, and only with a+// user that already exists. Returns the owner plus an HTTP status to use on error.+func (s *Server) resolveTokenOwner(ctx context.Context, caller *storage.User, requested string) (string, int, error) {+ requested = strings.TrimSpace(requested)+ if requested == "" || requested == caller.ID {+ return caller.ID, 0, nil+ }+ if caller.Role != "admin" {+ return "", http.StatusForbidden, errors.New("forbidden: only admins may issue tokens on behalf of another user")+ }+ if _, err := s.store.GetUser(ctx, requested); err != nil {+ if err == storage.ErrNotFound {+ return "", http.StatusBadRequest, fmt.Errorf("unknown owner_id %q: the user must have logged in at least once", requested)+ }+ return "", http.StatusInternalServerError, errors.New("failed to look up owner")+ }+ return requested, 0, nil+}+func (s *Server) HandleUserRevoke(w http.ResponseWriter, r *http.Request) {user, err := s.authenticateUser(r)if err != nil {diff --git a/internal/controlplane/server_test.go b/internal/controlplane/server_test.goindex ff1e8185..53fa7768 100644--- a/internal/controlplane/server_test.go+++ b/internal/controlplane/server_test.go@@ -1386,3 +1386,78 @@ func TestAuthDenialPaths(t *testing.T) {}})}++// TestBootstrapTokenOwnerPropagatesToNode ensures a node enrolled with a user-owned+// bootstrap token is attributed to that user, which is what makes the console's+// per-user node listing work.+func TestBootstrapTokenOwnerPropagatesToNode(t *testing.T) {+ issuer, mintToken := startCustomMockOIDC(t)+ srv, store, baseURL := setupTestServer(t, issuer)+ defer func() {+ _ = srv.Close()+ _ = store.Close()+ }()+ srv.config.AutoApproveEnrollment = true++ ctx := context.Background()+ client := &http.Client{Timeout: 5 * time.Second}++ const ownerSub = "owner-sub-id"+ userJWT := mintToken(map[string]interface{}{"sub": ownerSub, "email": "[email protected]"})++ req, _ := http.NewRequest(http.MethodPost, baseURL+"/user/bootstrap-tokens",+ bytes.NewBufferString(`{"role":"`+api.RoleNode+`","max_usages":1}`))+ req.Header.Set("Content-Type", "application/json")+ req.Header.Set("Authorization", "Bearer "+userJWT)+ resp, err := client.Do(req)+ if err != nil {+ t.Fatalf("failed to create bootstrap token: %v", err)+ }+ if resp.StatusCode != http.StatusCreated {+ body, _ := io.ReadAll(resp.Body)+ _ = resp.Body.Close()+ t.Fatalf("unexpected status creating token: %s (%s)", resp.Status, body)+ }+ var tokenDetails struct {+ Token string `json:"token"`+ OwnerID string `json:"owner_id"`+ }+ _ = json.NewDecoder(resp.Body).Decode(&tokenDetails)+ _ = resp.Body.Close()++ if tokenDetails.OwnerID != ownerSub {+ t.Fatalf("token owner = %q, want %q", tokenDetails.OwnerID, ownerSub)+ }++ privNode, pubNode, err := crypto.GenerateKeyPair(crypto.Ed25519, -1)+ if err != nil {+ t.Fatal(err)+ }+ pID, _ := peer.IDFromPrivateKey(privNode)+ pubBytes, _ := crypto.MarshalPublicKey(pubNode)++ enrollData, _ := proto.Marshal(&api.BootstrapEnrollRequest{+ BootstrapToken: tokenDetails.Token,+ PeerId: pID.String(),+ PublicKey: pubBytes,+ RequestedRole: api.RoleNode,+ })+ resp, err = client.Post(baseURL+"/enroll", "application/x-protobuf", bytes.NewBuffer(enrollData))+ if err != nil {+ t.Fatalf("failed to enroll: %v", err)+ }+ if resp.StatusCode != http.StatusOK {+ body, _ := io.ReadAll(resp.Body)+ _ = resp.Body.Close()+ t.Fatalf("unexpected enroll status: %s (%s)", resp.Status, body)+ }+ _ = resp.Body.Close()++ enrolled, err := store.GetNode(ctx, pID.String())+ if err != nil {+ t.Fatalf("failed to load enrolled node: %v", err)+ }+ if enrolled.OwnerID != ownerSub {+ t.Errorf("enrolled node owner = %q, want %q", enrolled.OwnerID, ownerSub)+ }+}diff --git a/tests/integration/bootstrap_token_owner_test.go b/tests/integration/bootstrap_token_owner_test.gonew file mode 100644index 00000000..1ba67043--- /dev/null+++ b/tests/integration/bootstrap_token_owner_test.go@@ -0,0 +1,216 @@+// 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 integration_test++import (+ "bytes"+ "context"+ "encoding/json"+ "io"+ "net/http"+ "path/filepath"+ "testing"+ "time"++ "github.com/google/sam/api"+ "github.com/google/sam/internal/controlplane"+ "github.com/google/sam/internal/storage"+)++// startTokenTestControlPlane brings up a control plane wired to a mock OIDC provider+// and returns its base URL, a JWT minter, and the backing store.+func startTokenTestControlPlane(t *testing.T) (string, func(claims map[string]interface{}) string, storage.Store) {+ t.Helper()++ oidcURL, mintToken := startCustomMockOIDC(t)++ store, err := storage.NewSQLStore("sqlite", filepath.Join(t.TempDir(), "cp.db"))+ if err != nil {+ t.Fatalf("failed to create store: %v", err)+ }+ t.Cleanup(func() { _ = store.Close() })++ opts := controlplane.Options{+ ListenAddr: "127.0.0.1:0",+ AdminToken: "test-admin-token",+ OIDCIssuer: oidcURL,+ AllowedAudiences: []string{"sam-mesh-audience"},+ }+ srv, err := controlplane.NewServer(opts, store)+ if err != nil {+ t.Fatalf("failed to create control plane: %v", err)+ }+ if err := srv.Start(); err != nil {+ t.Fatalf("failed to start control plane: %v", err)+ }+ t.Cleanup(func() { _ = srv.Close() })++ return "http://" + srv.Addr(), mintToken, store+}++type tokenResponse struct {+ ID string `json:"id"`+ Token string `json:"token"`+ Role string `json:"role"`+ OwnerID string `json:"owner_id"`+}++// requestBootstrapToken posts to /user/bootstrap-tokens and returns the status and decoded body.+func requestBootstrapToken(t *testing.T, baseURL, bearer string, payload map[string]interface{}) (int, tokenResponse, string) {+ t.Helper()++ body, err := json.Marshal(payload)+ if err != nil {+ t.Fatalf("failed to marshal payload: %v", err)+ }+ req, err := http.NewRequest(http.MethodPost, baseURL+"/user/bootstrap-tokens", bytes.NewReader(body))+ if err != nil {+ t.Fatalf("failed to build request: %v", err)+ }+ req.Header.Set("Content-Type", "application/json")+ req.Header.Set("Authorization", "Bearer "+bearer)++ resp, err := (&http.Client{Timeout: 5 * time.Second}).Do(req)+ if err != nil {+ t.Fatalf("request failed: %v", err)+ }+ defer func() { _ = resp.Body.Close() }()++ raw, err := io.ReadAll(resp.Body)+ if err != nil {+ t.Fatalf("failed to read body: %v", err)+ }+ var decoded tokenResponse+ if resp.StatusCode == http.StatusCreated {+ if err := json.Unmarshal(raw, &decoded); err != nil {+ t.Fatalf("failed to decode body %q: %v", raw, err)+ }+ }+ return resp.StatusCode, decoded, string(raw)+}++// TestBootstrapTokenOwnership pins down who ends up owning a token generated through+// the console: the owner defaults to the caller's session and only admins may override it.+func TestBootstrapTokenOwnership(t *testing.T) {+ baseURL, mintToken, store := startTokenTestControlPlane(t)+ ctx := context.Background()++ const (+ aliceSub = "alice-subject-id"+ bobSub = "bob-subject-id"+ )+ aliceJWT := mintToken(map[string]interface{}{"sub": aliceSub, "email": "[email protected]"})+ bobJWT := mintToken(map[string]interface{}{"sub": bobSub, "email": "[email protected]"})++ // Both users must exist in the store before an admin can delegate to them,+ // which happens implicitly on first authenticated call.+ for _, jwt := range []string{aliceJWT, bobJWT} {+ if status, _, body := requestBootstrapToken(t, baseURL, jwt, map[string]interface{}{+ "role": api.RoleNode,+ }); status != http.StatusCreated {+ t.Fatalf("failed to auto-register user: status %d body %q", status, body)+ }+ }++ t.Run("owner defaults to session when omitted", func(t *testing.T) {+ status, res, body := requestBootstrapToken(t, baseURL, aliceJWT, map[string]interface{}{+ "role": api.RoleNode,+ "description": "no owner supplied",+ })+ if status != http.StatusCreated {+ t.Fatalf("expected 201, got %d: %s", status, body)+ }+ if res.OwnerID != aliceSub {+ t.Errorf("expected owner %q, got %q", aliceSub, res.OwnerID)+ }+ assertStoredOwner(t, ctx, store, res.ID, aliceSub)+ })++ t.Run("owner may be set explicitly to self", func(t *testing.T) {+ status, res, body := requestBootstrapToken(t, baseURL, aliceJWT, map[string]interface{}{+ "role": api.RoleNode,+ "owner_id": aliceSub,+ })+ if status != http.StatusCreated {+ t.Fatalf("expected 201, got %d: %s", status, body)+ }+ if res.OwnerID != aliceSub {+ t.Errorf("expected owner %q, got %q", aliceSub, res.OwnerID)+ }+ })++ t.Run("non-admin cannot issue on behalf of another user", func(t *testing.T) {+ status, _, body := requestBootstrapToken(t, baseURL, aliceJWT, map[string]interface{}{+ "role": api.RoleNode,+ "owner_id": bobSub,+ })+ if status != http.StatusForbidden {+ t.Fatalf("expected 403, got %d: %s", status, body)+ }+ })++ t.Run("admin may issue on behalf of an existing user", func(t *testing.T) {+ status, res, body := requestBootstrapToken(t, baseURL, "test-admin-token", map[string]interface{}{+ "role": api.RoleNode,+ "owner_id": bobSub,+ })+ if status != http.StatusCreated {+ t.Fatalf("expected 201, got %d: %s", status, body)+ }+ if res.OwnerID != bobSub {+ t.Errorf("expected owner %q, got %q", bobSub, res.OwnerID)+ }+ assertStoredOwner(t, ctx, store, res.ID, bobSub)+ })++ t.Run("admin cannot issue on behalf of an unknown user", func(t *testing.T) {+ status, _, body := requestBootstrapToken(t, baseURL, "test-admin-token", map[string]interface{}{+ "role": api.RoleNode,+ "owner_id": "nobody-has-ever-logged-in-as-this",+ })+ if status != http.StatusBadRequest {+ t.Fatalf("expected 400, got %d: %s", status, body)+ }+ })++ t.Run("non-admin cannot request router role", func(t *testing.T) {+ status, _, body := requestBootstrapToken(t, baseURL, aliceJWT, map[string]interface{}{+ "role": api.RoleRouter,+ })+ if status != http.StatusForbidden {+ t.Fatalf("expected 403, got %d: %s", status, body)+ }+ })++ t.Run("unauthenticated requests are rejected", func(t *testing.T) {+ status, _, body := requestBootstrapToken(t, baseURL, "not-a-real-token", map[string]interface{}{+ "role": api.RoleNode,+ })+ if status != http.StatusUnauthorized {+ t.Fatalf("expected 401, got %d: %s", status, body)+ }+ })+}++func assertStoredOwner(t *testing.T, ctx context.Context, store storage.Store, tokenID, wantOwner string) {+ t.Helper()+ stored, err := store.GetBootstrapToken(ctx, tokenID)+ if err != nil {+ t.Fatalf("failed to load token %s: %v", tokenID, err)+ }+ if stored.OwnerID != wantOwner {+ t.Errorf("persisted owner = %q, want %q", stored.OwnerID, wantOwner)+ }+}