Skip to content

Agent Mesh

console: fix Save & Apply Policy, and report it without blocking

Antonio Ojea1a0a0082c9e5
diff --git a/cmd/sam-console/public/app.js b/cmd/sam-console/public/app.js
index f086170a..433d679e 100644
--- a/cmd/sam-console/public/app.js
+++ b/cmd/sam-console/public/app.js
@@ -1,5 +1,6 @@
const DEFAULT_TAB = 'overview';
const REFRESH_INTERVAL_MS = 15000;
+const TOAST_TIMEOUT_MS = 5000;
let refreshTimer = null;
let refreshInFlight = false;
@@ -175,7 +176,7 @@ async function loginWithToken(inputId) {
await loadData();
showApp();
} catch (error) {
- alert('Login failed: ' + error.message);
+ showToast('Login failed: ' + error.message, 'error');
}
}
@@ -274,6 +275,34 @@ function announce(message) {
}
}
+// alert() blocks the event loop, so it also stalls the refresh timer, and it is
+// unusable on the mobile layout.
+function showToast(message, type = 'info') {
+ const container = document.getElementById('toast-container');
+ if (!container) return;
+
+ const toast = document.createElement('div');
+ toast.className = `toast toast-${type}`;
+
+ const text = document.createElement('span');
+ text.textContent = message;
+ toast.appendChild(text);
+
+ const dismiss = document.createElement('button');
+ dismiss.className = 'toast-dismiss';
+ dismiss.type = 'button';
+ dismiss.setAttribute('aria-label', 'Dismiss notification');
+ dismiss.textContent = '\u00d7';
+ dismiss.addEventListener('click', () => toast.remove());
+ toast.appendChild(dismiss);
+
+ container.appendChild(toast);
+ // Errors stay until dismissed; the operator usually needs to act on them.
+ if (type !== 'error') {
+ setTimeout(() => toast.remove(), TOAST_TIMEOUT_MS);
+ }
+}
+
function setTableMessage(tbodyID, colspan, message, isError = false) {
const tbody = document.getElementById(tbodyID);
if (!tbody) return;
@@ -405,7 +434,7 @@ async function actionRequest(url, method = 'POST', body = null) {
loadData();
return true;
} catch (error) {
- alert('Action failed: ' + error.message);
+ showToast('Action failed: ' + error.message, 'error');
throw error;
}
}
@@ -661,44 +690,24 @@ window.copyGeneratedToken = async function() {
setTimeout(() => { btn.textContent = 'Copy'; }, 2000);
};
-function writeVarint(value) {
- const bytes = [];
- while (value > 127) {
- bytes.push((value & 127) | 128);
- value >>= 7;
- }
- bytes.push(value);
- return bytes;
-}
-
window.savePolicy = async function() {
const yamlContent = document.getElementById('policy-yaml').value;
- const encoder = new TextEncoder();
- const yamlBytes = encoder.encode(yamlContent);
-
- const lenBytes = writeVarint(yamlBytes.length);
- const pbBytes = new Uint8Array(1 + lenBytes.length + yamlBytes.length);
- pbBytes[0] = 0x0a; // field tag 1 (YamlContent)
- pbBytes.set(lenBytes, 1);
- pbBytes.set(yamlBytes, 1 + lenBytes.length);
-
- const headers = { 'Content-Type': 'application/x-protobuf' };
try {
const response = await fetch('api/policies', {
method: 'POST',
- headers: headers,
- body: pbBytes
+ headers: { 'Content-Type': 'application/yaml' },
+ body: yamlContent
}); if (response.ok) {
policyBaseline = yamlContent;
- alert('Mesh policy updated and applied successfully!');
+ showToast('Mesh policy updated and applied.', 'success');
loadData();
} else {
const text = await response.text();
- alert('Failed to save policy: ' + text);
+ showToast('Failed to save policy: ' + text.trim(), 'error');
}
} catch (err) {
- alert('Network error: ' + err.message);
+ showToast('Network error: ' + err.message, 'error');
}
};
diff --git a/cmd/sam-console/public/index.html b/cmd/sam-console/public/index.html
index 8df90f4b..de51a8c4 100644
--- a/cmd/sam-console/public/index.html
+++ b/cmd/sam-console/public/index.html
@@ -328,6 +328,8 @@
</div>
</main>
</div>
+ <!-- Transient action feedback, announced as it arrives. -->
+ <div id="toast-container" class="toast-container" role="status" aria-live="polite"></div>
<script src="app.js"></script>
</body>
</html>
diff --git a/cmd/sam-console/public/style.css b/cmd/sam-console/public/style.css
index c7fb0dab..22707677 100644
--- a/cmd/sam-console/public/style.css
+++ b/cmd/sam-console/public/style.css
@@ -47,6 +47,64 @@ body {
border: 0;
}
+/* Above the landing overlay, so a failed login is still readable. */
+.toast-container {
+ position: fixed;
+ top: 20px;
+ right: 20px;
+ z-index: 2000;
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+ max-width: min(380px, calc(100vw - 40px));
+ pointer-events: none;
+}
+
+.toast {
+ display: flex;
+ align-items: flex-start;
+ gap: 12px;
+ padding: 12px 16px;
+ border-radius: 8px;
+ background-color: var(--bg-surface);
+ border: 1px solid var(--border-color);
+ border-left: 3px solid var(--accent);
+ color: var(--text-primary);
+ font-size: 0.9rem;
+ box-shadow: 0 8px 24px rgba(0, 0, 0, 0.4);
+ animation: toastIn 0.2s ease;
+ pointer-events: auto;
+ overflow-wrap: anywhere;
+}
+
+.toast-success {
+ border-left-color: var(--success);
+}
+
+.toast-error {
+ border-left-color: var(--danger);
+}
+
+.toast-dismiss {
+ margin-left: auto;
+ background: none;
+ border: none;
+ color: var(--text-secondary);
+ font-size: 1.1rem;
+ line-height: 1;
+ cursor: pointer;
+ padding: 0 2px;
+}
+
+.toast-dismiss:hover {
+ color: var(--text-primary);
+}
+
+@keyframes toastIn {
+ from { opacity: 0; transform: translateX(20px); }
+ to { opacity: 1; transform: translateX(0); }
+}
+
/* Layout */
.app-container {
display: flex;
diff --git a/internal/controlplane/server.go b/internal/controlplane/server.go
index 547fd2e3..ee413450 100644
--- a/internal/controlplane/server.go
+++ b/internal/controlplane/server.go
@@ -29,6 +29,7 @@ import (
"io"
"net"
"net/http"
+ "sort"
"strings"
"sync"
"time"
@@ -976,21 +977,30 @@ func (s *Server) HandlePolicies(w http.ResponseWriter, r *http.Request) {
}
defer func() { _ = r.Body.Close() }()
- var req api.PolicyConfigUpdateRequest
- if strings.HasPrefix(r.Header.Get("Content-Type"), "application/json") {
+ req := &api.PolicyConfigUpdateRequest{}
+ contentType := r.Header.Get("Content-Type")
+ switch {
+ case strings.HasPrefix(contentType, "application/json"):
unmarshaler := protojson.UnmarshalOptions{DiscardUnknown: true}
- if err := unmarshaler.Unmarshal(body, &req); err != nil {
+ if err := unmarshaler.Unmarshal(body, req); err != nil {
http.Error(w, "Invalid JSON format: "+err.Error(), http.StatusBadRequest)
return
}
- } else {
- if err := proto.Unmarshal(body, &req); err != nil {
+ case strings.HasPrefix(contentType, "application/yaml"), strings.HasPrefix(contentType, "text/yaml"):
+ parsed, err := parsePolicyYAML(body)
+ if err != nil {
+ http.Error(w, "Invalid YAML format: "+err.Error(), http.StatusBadRequest)
+ return
+ }
+ req = parsed
+ default:
+ if err := proto.Unmarshal(body, req); err != nil {
http.Error(w, "Invalid request format", http.StatusBadRequest)
return
}
}
- if err := validatePolicyConfig(&req); err != nil {
+ if err := validatePolicyConfig(req); err != nil {
http.Error(w, "Invalid policy configuration: "+err.Error(), http.StatusBadRequest)
return
}
@@ -1743,34 +1753,8 @@ func (s *Server) HandleUserStatus(w http.ResponseWriter, r *http.Request) {
logger.Errorf("Failed to list policy: %v", err)
}
- type displayRole struct {
- AllowedServices []string `yaml:"allowed_services"`
- AllowedTargets []string `yaml:"allowed_targets"`
- }
- type displayBinding struct {
- Role string `yaml:"role"`
- Members []string `yaml:"members"`
- }
- displayMap := map[string]interface{}{
- "roles": make(map[string]displayRole),
- "bindings": make([]displayBinding, 0),
- }
-
- for _, role := range roles {
- displayMap["roles"].(map[string]displayRole)[role.Name] = displayRole{
- AllowedServices: role.AllowedServices,
- AllowedTargets: role.AllowedTargets,
- }
- }
- for _, b := range bindings {
- displayMap["bindings"] = append(displayMap["bindings"].([]displayBinding), displayBinding{
- Role: b.Role,
- Members: b.Members,
- })
- }
-
var policyYAML string
- if yamlBytes, err := yaml.Marshal(displayMap); err == nil {
+ if yamlBytes, err := yaml.Marshal(newPolicyDocument(roles, bindings)); err == nil {
policyYAML = string(yamlBytes)
}
@@ -2029,6 +2013,81 @@ func toStringSlice(val any) []string {
return nil
}
+// policyDocument is the YAML rendering of a mesh policy. It is both what
+// /user/status and /admin/status hand the console and what POST /policies
+// accepts back, so an operator can round-trip the text they were shown. Keep
+// every PolicyRole field represented here: anything omitted is silently dropped
+// on save.
+type policyDocument struct {
+ Roles map[string]policyDocumentRole `yaml:"roles"`
+ Bindings []policyDocumentBinding `yaml:"bindings"`
+}
+
+type policyDocumentRole struct {
+ AllowedServices []string `yaml:"allowed_services"`
+ AllowedTargets []string `yaml:"allowed_targets"`
+ CustomDatalog []string `yaml:"custom_datalog,omitempty"`
+}
+
+type policyDocumentBinding struct {
+ Role string `yaml:"role"`
+ Members []string `yaml:"members"`
+}
+
+func newPolicyDocument(roles []*api.PolicyRole, bindings []*api.PolicyBinding) policyDocument {
+ doc := policyDocument{
+ Roles: make(map[string]policyDocumentRole, len(roles)),
+ Bindings: make([]policyDocumentBinding, 0, len(bindings)),
+ }
+ for _, role := range roles {
+ if role == nil {
+ continue
+ }
+ doc.Roles[role.Name] = policyDocumentRole{
+ AllowedServices: role.AllowedServices,
+ AllowedTargets: role.AllowedTargets,
+ CustomDatalog: role.CustomDatalog,
+ }
+ }
+ for _, b := range bindings {
+ if b == nil {
+ continue
+ }
+ doc.Bindings = append(doc.Bindings, policyDocumentBinding{Role: b.Role, Members: b.Members})
+ }
+ return doc
+}
+
+// parsePolicyYAML converts the console's editable YAML back into an update
+// request. Role order is not preserved by the YAML map, but the policy is a set,
+// and validatePolicyConfig rejects duplicates.
+func parsePolicyYAML(body []byte) (*api.PolicyConfigUpdateRequest, error) {
+ var doc policyDocument
+ if err := yaml.UnmarshalStrict(body, &doc); err != nil {
+ return nil, err
+ }
+
+ req := &api.PolicyConfigUpdateRequest{}
+ names := make([]string, 0, len(doc.Roles))
+ for name := range doc.Roles {
+ names = append(names, name)
+ }
+ sort.Strings(names)
+ for _, name := range names {
+ role := doc.Roles[name]
+ req.Roles = append(req.Roles, &api.PolicyRole{
+ Name: name,
+ AllowedTargets: role.AllowedTargets,
+ AllowedServices: role.AllowedServices,
+ CustomDatalog: role.CustomDatalog,
+ })
+ }
+ for _, b := range doc.Bindings {
+ req.Bindings = append(req.Bindings, &api.PolicyBinding{Role: b.Role, Members: b.Members})
+ }
+ return req, nil
+}
+
// maxIdentityFactBudget bounds the worst-case number of Datalog facts a policy
// config could let a single identity accumulate across all of its resolved
// roles. biscuit-go's authorizer defaults to rejecting worlds beyond ~1000
diff --git a/internal/controlplane/server_test.go b/internal/controlplane/server_test.go
index f50efb63..f94aa39c 100644
--- a/internal/controlplane/server_test.go
+++ b/internal/controlplane/server_test.go
@@ -42,6 +42,7 @@ import (
"github.com/libp2p/go-libp2p/core/crypto"
"github.com/libp2p/go-libp2p/core/peer"
"google.golang.org/protobuf/proto"
+ "gopkg.in/yaml.v2"
)
func startCustomMockOIDC(t *testing.T) (string, func(claims map[string]interface{}) string) {
@@ -438,6 +439,82 @@ func TestNodeAndRouterRegistrationFlow(t *testing.T) {
}
}
+// The console shows the operator this YAML and posts the edited text straight
+// back, so anything the render drops is silently deleted from the mesh policy on
+// the next save.
+func TestPolicyYAMLRoundTrip(t *testing.T) {
+ roles := []*api.PolicyRole{
+ {
+ Name: "dev",
+ AllowedServices: []string{"mcp://git"},
+ AllowedTargets: []string{"node:abc"},
+ CustomDatalog: []string{"right(\"data:read\");"},
+ },
+ {
+ Name: "ops",
+ AllowedServices: []string{"mcp://deploy"},
+ },
+ }
+ bindings := []*api.PolicyBinding{
+ {Role: "dev", Members: []string{"group:developers"}},
+ {Role: "ops", Members: []string{"user:root"}},
+ }
+
+ rendered, err := yaml.Marshal(newPolicyDocument(roles, bindings))
+ if err != nil {
+ t.Fatalf("rendering the policy document: %v", err)
+ }
+
+ parsed, err := parsePolicyYAML(rendered)
+ if err != nil {
+ t.Fatalf("parsing back the rendered policy: %v\n%s", err, rendered)
+ }
+
+ if len(parsed.Roles) != len(roles) {
+ t.Fatalf("got %d roles, want %d", len(parsed.Roles), len(roles))
+ }
+ byName := make(map[string]*api.PolicyRole, len(parsed.Roles))
+ for _, r := range parsed.Roles {
+ byName[r.Name] = r
+ }
+ for _, want := range roles {
+ got, ok := byName[want.Name]
+ if !ok {
+ t.Fatalf("role %q was lost in the round trip", want.Name)
+ }
+ if !proto.Equal(got, want) {
+ t.Errorf("role %q round-tripped as %v, want %v", want.Name, got, want)
+ }
+ }
+
+ if len(parsed.Bindings) != len(bindings) {
+ t.Fatalf("got %d bindings, want %d", len(parsed.Bindings), len(bindings))
+ }
+ for i, want := range bindings {
+ if !proto.Equal(parsed.Bindings[i], want) {
+ t.Errorf("binding %d round-tripped as %v, want %v", i, parsed.Bindings[i], want)
+ }
+ }
+
+ // The result must survive the same validation a POST applies.
+ if err := validatePolicyConfig(parsed); err != nil {
+ t.Errorf("round-tripped policy failed validation: %v", err)
+ }
+}
+
+func TestParsePolicyYAMLRejectsGarbage(t *testing.T) {
+ for name, body := range map[string]string{
+ "not yaml": "\tnot: [valid",
+ "wrong shape": "roles: a string",
+ "unknown field": "roles: {}\nbindings: []\nsurprise: 1",
+ "scalar document": "42",
+ } {
+ if _, err := parsePolicyYAML([]byte(body)); err == nil {
+ t.Errorf("%s: parsePolicyYAML accepted %q", name, body)
+ }
+ }
+}
+
func TestPoliciesConfigurationREST(t *testing.T) {
issuer, _ := startCustomMockOIDC(t)
srv, store, baseURL := setupTestServer(t, issuer)
diff --git a/tests/ui/console.spec.js b/tests/ui/console.spec.js
index f352086f..fd6ce345 100644
--- a/tests/ui/console.spec.js
+++ b/tests/ui/console.spec.js
@@ -215,3 +215,32 @@ test('navigation is keyboard operable and refreshes are announced', async ({ pag
await expect(page.locator('#live-status')).toHaveText(/nodes, .* routers/);
});
+
+// A blocking alert() would also stall the refresh timer, so feedback must not
+// come from a native dialog.
+test('action feedback is a dismissible toast, not a native dialog', async ({ page }) => {
+ await login(page);
+ await page.click('.nav-item[data-target="policy"]');
+
+ let dialogs = 0;
+ page.on('dialog', async (d) => {
+ dialogs += 1;
+ await d.dismiss();
+ });
+
+ await page.fill('#policy-yaml', '# applied by playwright\n');
+ await page.click('button:has-text("Save & Apply Policy")');
+
+ const toast = page.locator('#toast-container .toast');
+ await expect(toast).toHaveClass(/toast-success/);
+ await expect(toast).toContainText('Mesh policy updated');
+ expect(dialogs).toBe(0);
+
+ await toast.locator('.toast-dismiss').click();
+ await expect(toast).toHaveCount(0);
+
+ // Saving cleared the dirty flag, so leaving must not prompt.
+ await page.click('.nav-item[data-target="overview"]');
+ await expect(page.locator('#view-overview')).toBeVisible();
+ expect(dialogs).toBe(0);
+});