Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
console: keep session credentials out of JavaScript
Antonio Ojea07625d9ae026
diff --git a/cmd/sam-console/public/app.js b/cmd/sam-console/public/app.jsindex c68e2c89..9d257dc4 100644--- a/cmd/sam-console/public/app.js+++ b/cmd/sam-console/public/app.js@@ -1,32 +1,64 @@+const DEFAULT_TAB = 'overview';+const REFRESH_INTERVAL_MS = 15000;++let refreshTimer = null;+let refreshInFlight = false;+document.addEventListener('DOMContentLoaded', () => {// Navigation handlingconst navItems = document.querySelectorAll('.nav-item');- const viewSections = document.querySelectorAll('.view-section');navItems.forEach(item => {item.addEventListener('click', (e) => {e.preventDefault();- const target = e.currentTarget.getAttribute('data-target');-- // Update active states- navItems.forEach(n => n.classList.remove('active'));- e.currentTarget.classList.add('active');-- viewSections.forEach(v => v.classList.remove('active'));- document.getElementById(`view-${target}`).classList.add('active');-- // Optionally fetch data specifically for that view if needed- // Currently, loadData() fetches everything from the status endpoint.+ switchTab(e.currentTarget.getAttribute('data-target'));// On mobile the sidebar is an overlay drawer; close it after navigating.closeSidebar();});});+ window.addEventListener('hashchange', () => switchTab(tabFromHash()));+ switchTab(tabFromHash());+// Check auth status on loadcheckAuthAndLoad();});+function tabFromHash() {+ const raw = window.location.hash.replace(/^#/, '');+ let target = raw;+ try {+ target = decodeURIComponent(raw);+ } catch (e) {+ // A malformed escape sequence is just an unknown tab.+ }+ return document.getElementById(`view-${target}`) ? target : DEFAULT_TAB;+}++function startAutoRefresh() {+ if (refreshTimer !== null) {+ return;+ }+ refreshTimer = setInterval(() => {+ // Polling a backgrounded tab only burns control-plane calls.+ if (document.visibilityState !== 'visible' || refreshInFlight) {+ return;+ }+ refreshInFlight = true;+ loadData()+ .catch(() => {})+ .finally(() => { refreshInFlight = false; });+ }, REFRESH_INTERVAL_MS);+}++function stopAutoRefresh() {+ if (refreshTimer !== null) {+ clearInterval(refreshTimer);+ refreshTimer = null;+ }+}+window.toggleSidebar = function() {document.querySelector('.sidebar').classList.toggle('open');document.getElementById('sidebar-scrim').classList.toggle('active');@@ -53,62 +85,72 @@ async function checkAuthAndLoad() {try {await loadData();- document.getElementById('landing-page').classList.remove('active');- document.getElementById('app-container').style.display = 'flex';+ showApp();} catch (error) {- document.getElementById('landing-page').classList.add('active');- document.getElementById('app-container').style.display = 'none';+ showLandingPage();}}+function showApp() {+ document.getElementById('landing-page').classList.remove('active');+ document.getElementById('app-container').style.display = 'flex';+ startAutoRefresh();+}++function showLandingPage() {+ stopAutoRefresh();+ document.getElementById('landing-page').classList.add('active');+ document.getElementById('app-container').style.display = 'none';+}+window.redirectToSSO = function() {window.location.href = 'auth/login';};-window.loginOIDC = function() {- const token = document.getElementById('oidc-token-input').value.trim();- if (token) {- localStorage.setItem('sam_admin_token', token);- document.getElementById('landing-page').classList.remove('active');- document.getElementById('app-container').style.display = 'flex';- loadData();- }-};--function getAdminToken() {- let token = localStorage.getItem('sam_admin_token') || '';- token = token.trim();- if (token.toLowerCase().startsWith('bearer ')) {- token = token.substring(7).trim();+// Hands the token to the server, which stores it in an httpOnly cookie and+// attaches it to proxied API calls. Keeping it out of JS reach means an XSS in+// the console cannot read or exfiltrate mesh credentials.+async function startSession(token) {+ const response = await fetch('auth/token', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ token })+ });+ if (!response.ok) {+ throw new Error((await response.text()).trim() || `HTTP ${response.status}`);}- return token;}-window.saveAdminToken = function() {- const val = document.getElementById('admin-token-input').value.trim();- if (val) {- localStorage.setItem('sam_admin_token', val);- document.getElementById('landing-page').classList.remove('active');- document.getElementById('app-container').style.display = 'flex';- loadData();+async function loginWithToken(inputId) {+ const input = document.getElementById(inputId);+ const token = input.value.trim();+ if (!token) {+ return;+ }+ try {+ await startSession(token);+ input.value = '';+ await loadData();+ showApp();+ } catch (error) {+ alert('Login failed: ' + error.message);}}-function getAuthHeaders() {- const token = getAdminToken();- return token ? { 'Authorization': 'Bearer ' + token } : {};-}+window.loginOIDC = function() {+ loginWithToken('oidc-token-input');+};++window.saveAdminToken = function() {+ loginWithToken('admin-token-input');+};async function loadData() {try {// 1. Fetch user-scoped status- const response = await fetch('api/user/status', {- headers: getAuthHeaders()- });+ const response = await fetch('api/user/status');if (response.status === 401 || response.status === 403) {- localStorage.removeItem('sam_admin_token');- document.getElementById('landing-page').classList.add('active');- document.getElementById('app-container').style.display = 'none';+ showLandingPage();throw new Error('Unauthorized. Please login again.');}if (!response.ok) {@@ -124,9 +166,7 @@ async function loadData() {// 2. If user is admin, fetch full unfiltered admin statusif (role === 'admin') {- const adminResp = await fetch('api/admin/status', {- headers: getAuthHeaders()- });+ const adminResp = await fetch('api/admin/status');if (adminResp.ok) {data = await adminResp.json();}@@ -150,6 +190,11 @@ async function loadData() {if (role === 'admin') {renderUsersTable(data.users || []);renderEnrollmentsTable(data.enrollment_requests || []);+ } else {+ // Their nav entries are hidden, but clear the placeholders anyway so a+ // stale "Loading..." can never be observed.+ setTableMessage('table-users', 4, 'Restricted to administrators.');+ setTableMessage('table-enrollments', 4, 'Restricted to administrators.');}renderNodesTable(data.enrolled_nodes || []);renderRoutersTable(data.active_routers || []);@@ -164,16 +209,23 @@ async function loadData() {} catch (error) {console.error('Failed to load dashboard data:', error);- const errMsg = `<tr><td colspan="4" class="text-center" style="color: var(--danger)">Error loading data: ${error.message}</td></tr>`;- document.getElementById('table-users').innerHTML = errMsg;- document.getElementById('table-nodes').innerHTML = errMsg;- document.getElementById('table-enrollments').innerHTML = errMsg;- document.getElementById('table-routers').innerHTML = errMsg;- document.getElementById('table-bootstrap').innerHTML = `<tr><td colspan="5" class="text-center" style="color: var(--danger)">Error loading data: ${error.message}</td></tr>`;+ const errMsg = `Error loading data: ${error.message}`;+ setTableMessage('table-users', 4, errMsg, true);+ setTableMessage('table-nodes', 4, errMsg, true);+ setTableMessage('table-enrollments', 4, errMsg, true);+ setTableMessage('table-routers', 3, errMsg, true);+ setTableMessage('table-bootstrap', 5, errMsg, true);throw error;}}+function setTableMessage(tbodyID, colspan, message, isError = false) {+ const tbody = document.getElementById(tbodyID);+ if (!tbody) return;+ const style = isError ? ' style="color: var(--danger)"' : '';+ tbody.innerHTML = `<tr><td colspan="${colspan}" class="text-center"${style}>${escapeHTML(message)}</td></tr>`;+}+function renderUsersTable(users) {const tbody = document.getElementById('table-users');if (users.length === 0) {@@ -272,7 +324,7 @@ async function actionRequest(url, method = 'POST', body = null) {try {const options = {method,- headers: getAuthHeaders()+ headers: {}};if (body) {options.headers['Content-Type'] = 'application/json';@@ -281,9 +333,7 @@ async function actionRequest(url, method = 'POST', body = null) {const response = await fetch(url, options);if (response.status === 401 || response.status === 403) {- localStorage.removeItem('sam_admin_token');- document.getElementById('landing-page').classList.add('active');- document.getElementById('app-container').style.display = 'none';+ showLandingPage();throw new Error('Unauthorized. Please login again.');}if (!response.ok) {@@ -324,7 +374,7 @@ function revokeDevice(id) {}window.logout = function() {- localStorage.removeItem('sam_admin_token');+ stopAutoRefresh();window.location.href = 'auth/logout';};@@ -386,28 +436,46 @@ function updateUIForRole(role, userId) {function switchTab(target) {const navItems = document.querySelectorAll('.nav-item');const viewSections = document.querySelectorAll('.view-section');++ let activeNav = Array.from(navItems).find(n => n.getAttribute('data-target') === target);+ // A shared or stale link can point at a view this role is not allowed to see.+ if (!activeNav || activeNav.style.display === 'none') {+ target = DEFAULT_TAB;+ activeNav = Array.from(navItems).find(n => n.getAttribute('data-target') === target);+ }+navItems.forEach(n => n.classList.remove('active'));viewSections.forEach(v => v.classList.remove('active'));- const activeNav = Array.from(navItems).find(n => n.getAttribute('data-target') === target);- if (activeNav) activeNav.classList.add('active');+ if (activeNav) {+ activeNav.classList.add('active');+ activeNav.setAttribute('aria-current', 'page');+ }+ navItems.forEach(n => {+ if (n !== activeNav) n.removeAttribute('aria-current');+ });const activeView = document.getElementById(`view-${target}`);if (activeView) activeView.classList.add('active');++ // Guarded so the resulting hashchange does not re-enter this function.+ if (tabFromHash() !== target) {+ window.location.hash = target;+ }}function renderRouterTopography(routers) {const topoList = document.getElementById('router-topography-list');- topoList.innerHTML = '';if (routers.length === 0) {topoList.innerHTML = '<div style="grid-column: 1/-1; text-align: center; color: var(--text-secondary); padding: 2rem;">No active routers online in the mesh.</div>';return;}- routers.forEach(r => {+ topoList.innerHTML = routers.map(r => {const conns = r.ConnectedPeers || [];const dhtSize = r.DHTSize || 0;-+ const peerID = String(r.PeerID || '');+// Calculate remaining lease time in secondslet elapsed = 0;if (r.ExpiresAt) {@@ -416,12 +484,12 @@ function renderRouterTopography(routers) {const peersHTML = conns.length === 0? '<li>No connected peers</li>'- : conns.map(p => `<li>${p.substring(0, 15)}... (${p.substring(p.length - 8)})</li>`).join('');+ : conns.map(p => `<li>${escapeHTML(String(p).substring(0, 15))}... (${escapeHTML(String(p).slice(-8))})</li>`).join('');- topoList.innerHTML += `+ return `<div class="router-item-card"><div class="router-header">- <span class="router-peer-id" title="${r.PeerID}">${r.PeerID.substring(0, 12)}...${r.PeerID.substring(r.PeerID.length - 8)}</span>+ <span class="router-peer-id" title="${escapeHTML(peerID)}">${escapeHTML(peerID.substring(0, 12))}...${escapeHTML(peerID.slice(-8))}</span><span class="badge badge-approved">Lease: ${elapsed}s</span></div><div class="router-metrics">@@ -430,7 +498,7 @@ function renderRouterTopography(routers) {<div style="font-size: 0.7rem; color: var(--text-secondary)">Connections</div></div><div class="router-metric-item" style="border-left: 1px solid var(--border-color)">- <div class="router-metric-val">${dhtSize}</div>+ <div class="router-metric-val">${escapeHTML(String(dhtSize))}</div><div style="font-size: 0.7rem; color: var(--text-secondary)">DHT Size</div></div></div>@@ -438,7 +506,7 @@ function renderRouterTopography(routers) {<ul class="router-peers-list">${peersHTML}</ul></div>`;- });+ }).join('');}function renderBootstrapTokensTable(tokens) {@@ -449,15 +517,14 @@ function renderBootstrapTokensTable(tokens) {}tbody.innerHTML = tokens.map(token => {- const createdAt = new Date(token.CreatedAt).toLocaleString();const expiresAt = token.ExpiresAt && !token.ExpiresAt.startsWith('0001') ? new Date(token.ExpiresAt).toLocaleString() : 'Never';return `<tr>- <td><code>${token.ID.substring(0, 8)}...</code></td>- <td>${token.Role}</td>- <td><code>${token.OwnerID || '-'}</code></td>- <td>${token.UsagesCount} / ${token.MaxUsages}</td>- <td>${expiresAt}</td>+ <td><code>${escapeHTML(String(token.ID || '').substring(0, 8))}...</code></td>+ <td>${escapeHTML(token.Role)}</td>+ <td><code>${escapeHTML(token.OwnerID || '-')}</code></td>+ <td>${escapeHTML(String(token.UsagesCount))} / ${escapeHTML(String(token.MaxUsages))}</td>+ <td>${escapeHTML(expiresAt)}</td></tr>`;}).join('');@@ -544,16 +611,14 @@ window.savePolicy = async function() {pbBytes.set(lenBytes, 1);pbBytes.set(yamlBytes, 1 + lenBytes.length);- const headers = getAuthHeaders();- headers['Content-Type'] = 'application/x-protobuf';+ const headers = { 'Content-Type': 'application/x-protobuf' };try {const response = await fetch('api/policies', {method: 'POST',headers: headers,body: pbBytes- });- if (response.ok) {+ }); if (response.ok) {alert('Mesh policy updated and applied successfully!');loadData();} else {diff --git a/internal/console/server.go b/internal/console/server.goindex c00b8849..88226fb0 100644--- a/internal/console/server.go+++ b/internal/console/server.go@@ -14,6 +14,7 @@ import ("os""path""path/filepath"+ "strings""time""github.com/coreos/go-oidc/v3/oidc"@@ -140,6 +141,8 @@ func NewServer(cfg Config) (*Server, error) {routes.HandleFunc("/auth/session", s.HandleSession)}routes.HandleFunc("/auth/logout", s.HandleLogout)+ // Available without OIDC: the admin bearer token uses the same exchange.+ routes.HandleFunc("/auth/token", s.HandleTokenLogin)routes.HandleFunc("/info", s.HandleInfo)// Serve under BasePath too, so the links this server emits resolve without the proxy@@ -346,6 +349,80 @@ func (s *Server) HandleInfo(w http.ResponseWriter, r *http.Request) {})}+// maxTokenLoginBody bounds the login body; a JWT with generous claims stays well+// under this, and cookies larger than this would be dropped by browsers anyway.+const maxTokenLoginBody = 16 << 10++// HandleTokenLogin exchanges a token the operator pasted into the console for an+// httpOnly session cookie, so the credential is never reachable from JavaScript+// and an XSS in the console cannot exfiltrate mesh admin rights.+func (s *Server) HandleTokenLogin(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodPost {+ w.Header().Set("Allow", http.MethodPost)+ http.Error(w, "method not allowed", http.StatusMethodNotAllowed)+ return+ }+ // An HTML form cannot produce this content type, so a cross-origin POST is+ // forced through a CORS preflight this server never approves. Blocks an+ // attacker from planting their own session cookie in a victim's browser.+ if ct := r.Header.Get("Content-Type"); ct != "application/json" {+ http.Error(w, "expected Content-Type: application/json", http.StatusUnsupportedMediaType)+ return+ }++ var req struct {+ Token string `json:"token"`+ }+ if err := json.NewDecoder(io.LimitReader(r.Body, maxTokenLoginBody)).Decode(&req); err != nil {+ http.Error(w, "invalid request body", http.StatusBadRequest)+ return+ }++ token := strings.TrimSpace(req.Token)+ // Operators routinely paste the whole "Bearer <token>" header value.+ if fields := strings.Fields(token); len(fields) > 0 && strings.EqualFold(fields[0], "bearer") {+ token = strings.Join(fields[1:], " ")+ }+ if token == "" {+ http.Error(w, "token is required", http.StatusBadRequest)+ return+ }+ // net/http silently drops a cookie whose value needs quoting, which would+ // fail as a confusing 401 later. Reject it here instead.+ if !isValidCookieValue(token) {+ http.Error(w, "token contains characters that are not valid in a cookie", http.StatusBadRequest)+ return+ }++ scheme := "http"+ if r.TLS != nil || r.Header.Get("X-Forwarded-Proto") == "https" {+ scheme = "https"+ }++ http.SetCookie(w, &http.Cookie{+ Name: "sam_session",+ Value: token,+ Path: s.cfg.BasePath + "/",+ MaxAge: 24 * 3600,+ HttpOnly: true,+ Secure: scheme == "https",+ SameSite: http.SameSiteLaxMode,+ })+ w.WriteHeader(http.StatusNoContent)+}++// isValidCookieValue reports whether v can be sent verbatim as a cookie value,+// per the cookie-octet rule in RFC 6265 section 4.1.1.+func isValidCookieValue(v string) bool {+ for i := 0; i < len(v); i++ {+ c := v[i]+ if c < 0x21 || c > 0x7e || c == '"' || c == ',' || c == ';' || c == '\\' {+ return false+ }+ }+ return true+}+func generatePKCE() (string, string, error) {verifierBytes := make([]byte, 32)if _, err := rand.Read(verifierBytes); err != nil {diff --git a/internal/console/server_test.go b/internal/console/server_test.goindex 111e5657..a0009307 100644--- a/internal/console/server_test.go+++ b/internal/console/server_test.go@@ -8,6 +8,7 @@ import ("net""net/http""net/http/httptest"+ "strings""sync/atomic""testing""time"@@ -295,6 +296,126 @@ func TestNewServer_BasePathServesBothPrefixes(t *testing.T) {}}+// The console holds mesh admin credentials, so a pasted token must land in an+// httpOnly cookie rather than anywhere JavaScript can read it.+func TestHandleTokenLogin(t *testing.T) {+ controlPlane := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.WriteHeader(http.StatusOK) // empty /info: no OIDC, which the console tolerates+ }))+ defer controlPlane.Close()++ srv, err := NewServer(Config{+ ControlPlaneURL: controlPlane.URL,+ AdminToken: "test-admin-token",+ StaticDir: t.TempDir(),+ BasePath: "/console",+ })+ if err != nil {+ t.Fatalf("failed to create server: %v", err)+ }+ console := httptest.NewServer(srv.Handler())+ defer console.Close()++ post := func(t *testing.T, contentType, body string) *http.Response {+ t.Helper()+ req, err := http.NewRequest(http.MethodPost, console.URL+"/console/auth/token", strings.NewReader(body))+ if err != nil {+ t.Fatalf("build request: %v", err)+ }+ req.Header.Set("Content-Type", contentType)+ resp, err := console.Client().Do(req)+ if err != nil {+ t.Fatalf("POST /console/auth/token: %v", err)+ }+ return resp+ }++ sessionCookie := func(resp *http.Response) *http.Cookie {+ for _, c := range resp.Cookies() {+ if c.Name == "sam_session" {+ return c+ }+ }+ return nil+ }++ t.Run("sets an httpOnly session cookie", func(t *testing.T) {+ resp := post(t, "application/json", `{"token":"test-admin-token"}`)+ defer func() { _ = resp.Body.Close() }()+ if resp.StatusCode != http.StatusNoContent {+ t.Fatalf("got status %d, want %d", resp.StatusCode, http.StatusNoContent)+ }+ c := sessionCookie(resp)+ if c == nil {+ t.Fatal("no sam_session cookie set")+ }+ if c.Value != "test-admin-token" {+ t.Errorf("cookie value = %q, want %q", c.Value, "test-admin-token")+ }+ if !c.HttpOnly {+ t.Error("cookie is not HttpOnly, so an XSS could read the mesh admin token")+ }+ if c.Path != "/console/" {+ t.Errorf("cookie path = %q, want %q", c.Path, "/console/")+ }+ })++ t.Run("strips a Bearer prefix", func(t *testing.T) {+ resp := post(t, "application/json", `{"token":" BeArEr test-admin-token "}`)+ defer func() { _ = resp.Body.Close() }()+ c := sessionCookie(resp)+ if c == nil || c.Value != "test-admin-token" {+ t.Fatalf("cookie = %+v, want value %q", c, "test-admin-token")+ }+ })++ // An HTML form can only send these content types, so rejecting them is what+ // stops a cross-origin POST from planting an attacker's session cookie.+ t.Run("rejects form content types", func(t *testing.T) {+ for _, ct := range []string{"application/x-www-form-urlencoded", "text/plain", "multipart/form-data"} {+ resp := post(t, ct, `{"token":"test-admin-token"}`)+ _ = resp.Body.Close()+ if resp.StatusCode != http.StatusUnsupportedMediaType {+ t.Errorf("Content-Type %s: got status %d, want %d", ct, resp.StatusCode, http.StatusUnsupportedMediaType)+ }+ if c := sessionCookie(resp); c != nil {+ t.Errorf("Content-Type %s: session cookie was set anyway", ct)+ }+ }+ })++ t.Run("rejects bad tokens", func(t *testing.T) {+ for name, body := range map[string]string{+ "empty": `{"token":""}`,+ "whitespace only": `{"token":" "}`,+ "bearer with no token": `{"token":"Bearer "}`,+ "not json": `nonsense`,+ "cookie separator": `{"token":"abc;def"}`,+ "control char": `{"token":"abc\ndef"}`,+ } {+ resp := post(t, "application/json", body)+ _ = resp.Body.Close()+ if resp.StatusCode != http.StatusBadRequest {+ t.Errorf("%s: got status %d, want %d", name, resp.StatusCode, http.StatusBadRequest)+ }+ if c := sessionCookie(resp); c != nil {+ t.Errorf("%s: session cookie was set anyway", name)+ }+ }+ })++ t.Run("rejects GET", func(t *testing.T) {+ resp, err := console.Client().Get(console.URL + "/console/auth/token")+ if err != nil {+ t.Fatalf("GET /console/auth/token: %v", err)+ }+ defer func() { _ = resp.Body.Close() }()+ if resp.StatusCode != http.StatusMethodNotAllowed {+ t.Errorf("got status %d, want %d", resp.StatusCode, http.StatusMethodNotAllowed)+ }+ })+}+// BasePath is concatenated into cookie paths, redirect URLs and mux patterns, so malformed// flag values (trailing slash, missing leading slash) must be normalized where the flag is read.func TestNormalizeBasePath(t *testing.T) {diff --git a/tests/ui/console.spec.js b/tests/ui/console.spec.jsindex 2664c58f..6a22df2a 100644--- a/tests/ui/console.spec.js+++ b/tests/ui/console.spec.js@@ -105,3 +105,41 @@ test('omitting the owner attributes the token to the session user', async ({ pagawait expect(page.locator('#token-result-owner')).toHaveText('root-admin');});++// The console holds mesh admin credentials. If they were reachable from JS, a+// single XSS in this hand-written page would hand over the whole mesh.+test('the session credential is never exposed to JavaScript', async ({ page, context }) => {+ await login(page);++ const storage = await page.evaluate(() => JSON.stringify(window.localStorage));+ expect(storage).not.toContain(ADMIN_TOKEN);+ expect(await page.evaluate(() => document.cookie)).not.toContain(ADMIN_TOKEN);++ const session = (await context.cookies()).find((c) => c.name === 'sam_session');+ expect(session, 'sam_session cookie was not set').toBeTruthy();+ expect(session.httpOnly).toBe(true);+});++test('views are deep-linkable via the URL hash', async ({ page }) => {+ await login(page);++ await page.click('.nav-item[data-target="routers"]');+ await expect(page).toHaveURL(/#routers$/);++ // A reload must land back on the same view rather than resetting to Overview.+ await page.reload();+ await expect(page.locator('#view-routers')).toBeVisible();+ await expect(page.locator('#view-overview')).toBeHidden();+ await expect(page.locator('.nav-item[data-target="routers"]')).toHaveAttribute('aria-current', 'page');++ // Back returns to the previously selected view.+ await page.goBack();+ await expect(page.locator('#view-overview')).toBeVisible();+});++test('an unknown hash falls back to the overview', async ({ page }) => {+ await login(page);++ await page.goto('/#not-a-view');+ await expect(page.locator('#view-overview')).toBeVisible();+});