Skip to content

Agent Mesh

feat: implement OIDC PKCE redirect flow and deploy local Dex sandbox

Antonio Ojeacdeb984228a8
diff --git a/.github/k8s/sam-console-template.yaml b/.github/k8s/sam-console-template.yaml
new file mode 100644
index 00000000..fd4217fc
--- /dev/null
+++ b/.github/k8s/sam-console-template.yaml
@@ -0,0 +1,53 @@
+apiVersion: v1
+kind: Service
+metadata:
+ name: sam-console-${ENV_NAME}
+ namespace: ${NAMESPACE}
+spec:
+ ports:
+ - port: 8081
+ targetPort: 8081
+ protocol: TCP
+ name: http
+ selector:
+ app: sam-console-${ENV_NAME}
+---
+apiVersion: apps/v1
+kind: Deployment
+metadata:
+ name: sam-console-${ENV_NAME}
+ namespace: ${NAMESPACE}
+spec:
+ replicas: 1
+ selector:
+ matchLabels:
+ app: sam-console-${ENV_NAME}
+ template:
+ metadata:
+ labels:
+ app: sam-console-${ENV_NAME}
+ spec:
+ containers:
+ - name: sam-console
+ image: ${IMAGE_PREFIX}sam-console:${TAG}
+ imagePullPolicy: IfNotPresent
+ args:
+ - "--hub=http://sam-control-plane-${ENV_NAME}:8080"
+ - "--bind-addr=:8081"
+ - "--static-dir=/app/public"
+ - "--admin-token=$(SAM_ADMIN_TOKEN)"
+ env:
+ - name: SAM_ADMIN_TOKEN
+ valueFrom:
+ secretKeyRef:
+ name: sam-admin-token
+ key: token
+ ports:
+ - containerPort: 8081
+ resources:
+ requests:
+ cpu: 10m
+ memory: 32Mi
+ limits:
+ cpu: 100m
+ memory: 128Mi
diff --git a/Dockerfile.sam-console b/Dockerfile.sam-console
new file mode 100644
index 00000000..74025c52
--- /dev/null
+++ b/Dockerfile.sam-console
@@ -0,0 +1,17 @@
+FROM golang:1.26.4-alpine AS builder
+
+WORKDIR /src
+COPY go.mod go.sum ./
+RUN go mod download
+
+COPY . .
+RUN CGO_ENABLED=0 go build -o /bin/sam-console ./cmd/sam-console
+
+FROM gcr.io/distroless/static-debian12
+
+WORKDIR /app
+COPY --from=builder /bin/sam-console /usr/local/bin/sam-console
+COPY cmd/sam-console/public /app/public
+
+EXPOSE 8081
+ENTRYPOINT ["/usr/local/bin/sam-console"]
diff --git a/Makefile b/Makefile
index b0771e4d..66e9fd18 100644
--- a/Makefile
+++ b/Makefile
@@ -31,6 +31,7 @@ build: $(OUT_DIR)/libinterceptor.so
go build -v -o "$(OUT_DIR)/mcp-client" ./cmd/mcp-client
go build -v -o "$(OUT_DIR)/nano-init" ./cmd/nano-init
go build -v -o "$(OUT_DIR)/sam-box" ./cmd/sam-box
+ go build -v -o "$(OUT_DIR)/sam-console" ./cmd/sam-console
.PHONY: mobile-ffi-host mobile-ffi-android mobile-ffi-android-x86_64 mobile-ffi-ios mobile-ffi mobile-app-apk mobile-app-apk-emulator
@@ -182,6 +183,9 @@ docker-build-nano-init:
docker-build-sam-box:
docker build --load -t sam-box:local -f Dockerfile.sam-box .
-docker-build: docker-build-control-plane docker-build-router docker-build-node docker-build-mock-oidc docker-build-e2e-runtime docker-build-nano-init docker-build-sam-box
+docker-build-sam-console:
+ docker build --load -t sam-console:local -f Dockerfile.sam-console .
-.PHONY: docker-build-control-plane docker-build-router docker-build-node docker-build-mock-oidc docker-build-e2e-runtime docker-build-nano-init docker-build-sam-box docker-build
+docker-build: docker-build-control-plane docker-build-router docker-build-node docker-build-mock-oidc docker-build-e2e-runtime docker-build-nano-init docker-build-sam-box docker-build-sam-console
+
+.PHONY: docker-build-control-plane docker-build-router docker-build-node docker-build-mock-oidc docker-build-e2e-runtime docker-build-nano-init docker-build-sam-box docker-build-sam-console docker-build
diff --git a/cmd/sam-console/main.go b/cmd/sam-console/main.go
new file mode 100644
index 00000000..406fce17
--- /dev/null
+++ b/cmd/sam-console/main.go
@@ -0,0 +1,61 @@
+package main
+
+import (
+ "context"
+ "flag"
+ "log"
+ "net/http"
+ "os"
+ "os/signal"
+ "syscall"
+ "time"
+
+ "github.com/google/sam/internal/console"
+)
+
+func main() {
+ var (
+ hubURL = flag.String("hub", "http://localhost:8080", "URL of the SAM control plane")
+ adminToken = flag.String("admin-token", "", "Admin token for control plane authentication")
+ bindAddr = flag.String("bind-addr", ":8081", "Address to bind the console server")
+ staticDir = flag.String("static-dir", "public", "Directory containing static frontend files")
+ )
+ flag.Parse()
+
+ if *adminToken == "" {
+ log.Fatal("Admin token is required (via --admin-token)")
+ }
+
+ srv, err := console.NewServer(console.Config{
+ HubURL: *hubURL,
+ AdminToken: *adminToken,
+ StaticDir: *staticDir,
+ })
+ if err != nil {
+ log.Fatalf("Failed to initialize console server: %v", err)
+ }
+
+ httpSrv := &http.Server{
+ Addr: *bindAddr,
+ Handler: srv.Handler(),
+ }
+
+ go func() {
+ log.Printf("SAM Console listening on %s", *bindAddr)
+ if err := httpSrv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
+ log.Fatalf("Console server error: %v", err)
+ }
+ }()
+
+ ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
+ defer stop()
+
+ <-ctx.Done()
+ log.Println("Shutting down console server...")
+
+ shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ if err := httpSrv.Shutdown(shutdownCtx); err != nil {
+ log.Fatalf("Server shutdown failed: %v", err)
+ }
+}
diff --git a/cmd/sam-console/public/app.js b/cmd/sam-console/public/app.js
new file mode 100644
index 00000000..0265272e
--- /dev/null
+++ b/cmd/sam-console/public/app.js
@@ -0,0 +1,516 @@
+document.addEventListener('DOMContentLoaded', () => {
+ // Navigation handling
+ const 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.
+ });
+ });
+
+ // Check auth status on load
+ checkAuthAndLoad();
+});
+
+async function checkAuthAndLoad() {
+ try {
+ const infoResp = await fetch('/console/info');
+ if (infoResp.ok) {
+ const info = await infoResp.json();
+ const ssoGroup = document.getElementById('sso-login-group');
+ if (ssoGroup) {
+ ssoGroup.style.display = info.oidc_enabled ? 'block' : 'none';
+ }
+ }
+ } catch (e) {
+ console.error("Failed to load console auth info:", e);
+ }
+
+ try {
+ await loadData();
+ document.getElementById('landing-page').classList.remove('active');
+ document.getElementById('app-container').style.display = 'flex';
+ } catch (error) {
+ 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() {
+ return localStorage.getItem('sam_admin_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();
+ }
+}
+
+function getAuthHeaders() {
+ return {
+ 'Authorization': 'Bearer ' + getAdminToken()
+ };
+}
+
+async function loadData() {
+ try {
+ // 1. Fetch user-scoped status
+ const response = await fetch('/api/user/status', {
+ headers: getAuthHeaders()
+ });
+ 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';
+ throw new Error('Unauthorized. Please login again.');
+ }
+ if (!response.ok) {
+ throw new Error(`HTTP error! status: ${response.status}`);
+ }
+ let data = await response.json();
+
+ const role = data.user ? data.user.role : 'user';
+ const userId = data.user ? data.user.id : '';
+
+ // Update UI components depending on Role
+ updateUIForRole(role, userId);
+
+ // 2. If user is admin, fetch full unfiltered admin status
+ if (role === 'admin') {
+ const adminResp = await fetch('/api/admin/status', {
+ headers: getAuthHeaders()
+ });
+ if (adminResp.ok) {
+ data = await adminResp.json();
+ }
+ }
+
+ // Update Stats
+ const usersCount = (data.users && data.users.length) || 0;
+ const nodesCount = (data.enrolled_nodes && data.enrolled_nodes.length) || 0;
+ const routersCount = (data.active_routers && data.active_routers.length) || 0;
+ const reqsCount = (data.enrollment_requests && data.enrollment_requests.length) || 0;
+
+ document.getElementById('stat-users').innerText = usersCount;
+ document.getElementById('stat-nodes').innerText = nodesCount;
+ document.getElementById('stat-routers').innerText = routersCount;
+
+ // Count pending
+ const pendingCount = (data.enrollment_requests || []).filter(r => r.Status === 0 || r.Status === 'ENROLLMENT_STATUS_PENDING').length;
+ document.getElementById('stat-pending').innerText = pendingCount;
+
+ // Render Tables & Grid
+ if (role === 'admin') {
+ renderUsersTable(data.users || []);
+ renderEnrollmentsTable(data.enrollment_requests || []);
+ }
+ renderNodesTable(data.enrolled_nodes || []);
+ renderRoutersTable(data.active_routers || []);
+ renderRouterTopography(data.active_routers || []);
+ renderBootstrapTokensTable(data.bootstrap_tokens || []);
+
+ // Populate policy yaml if empty
+ const policyArea = document.getElementById('policy-yaml');
+ if (policyArea && !policyArea.value && data.policy_yaml) {
+ policyArea.value = data.policy_yaml;
+ }
+
+ } 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>`;
+ throw error;
+ }
+}
+
+function renderUsersTable(users) {
+ const tbody = document.getElementById('table-users');
+ if (users.length === 0) {
+ tbody.innerHTML = `<tr><td colspan="4" class="text-center">No users found</td></tr>`;
+ return;
+ }
+
+ tbody.innerHTML = users.map(user => `
+ <tr>
+ <td><code>${user.ID || '-'}</code></td>
+ <td>${user.Role || '-'}</td>
+ <td>${user.Name || '-'}</td>
+ <td>${user.Email || '-'}</td>
+ </tr>
+ `).join('');
+}
+
+function renderNodesTable(nodes) {
+ const tbody = document.getElementById('table-nodes');
+ if (nodes.length === 0) {
+ tbody.innerHTML = `<tr><td colspan="4" class="text-center">No enrolled nodes found</td></tr>`;
+ return;
+ }
+
+ tbody.innerHTML = nodes.map(node => `
+ <tr>
+ <td><code>${node.PeerID || '-'}</code></td>
+ <td>${node.Role || '-'}</td>
+ <td>${node.OwnerID || '-'}</td>
+ <td>
+ <div class="actions-cell">
+ <button class="btn btn-sm btn-danger" onclick="revokeDevice('${node.PeerID}')">Revoke</button>
+ </div>
+ </td>
+ </tr>
+ `).join('');
+}
+
+function getStatusBadge(status) {
+ if (status === 0 || status === 'ENROLLMENT_STATUS_PENDING') {
+ return `<span class="badge badge-pending">Pending</span>`;
+ } else if (status === 1 || status === 'ENROLLMENT_STATUS_APPROVED') {
+ return `<span class="badge badge-approved">Approved</span>`;
+ } else if (status === 2 || status === 'ENROLLMENT_STATUS_REJECTED') {
+ return `<span class="badge badge-rejected">Rejected</span>`;
+ }
+ return `<span class="badge">Unknown</span>`;
+}
+
+function renderEnrollmentsTable(reqs) {
+ const tbody = document.getElementById('table-enrollments');
+ if (reqs.length === 0) {
+ tbody.innerHTML = `<tr><td colspan="4" class="text-center">No enrollment requests found</td></tr>`;
+ return;
+ }
+
+ tbody.innerHTML = reqs.map(req => {
+ const isPending = req.Status === 0 || req.Status === 'ENROLLMENT_STATUS_PENDING';
+ let actions = '';
+ if (isPending) {
+ actions = `
+ <div class="actions-cell">
+ <button class="btn btn-sm btn-success" onclick="approveEnrollment('${req.ID}')">Approve</button>
+ <button class="btn btn-sm btn-danger" onclick="rejectEnrollment('${req.ID}')">Reject</button>
+ </div>
+ `;
+ }
+ return `
+ <tr>
+ <td><code>${req.ID || '-'}</code></td>
+ <td>${getStatusBadge(req.Status)}</td>
+ <td>${req.CreatedAt || '-'}</td>
+ <td>${actions}</td>
+ </tr>
+ `;
+ }).join('');
+}
+
+function renderRoutersTable(routers) {
+ const tbody = document.getElementById('table-routers');
+ if (routers.length === 0) {
+ tbody.innerHTML = `<tr><td colspan="3" class="text-center">No active routers found</td></tr>`;
+ return;
+ }
+
+ tbody.innerHTML = routers.map(router => `
+ <tr>
+ <td><code>${router.PeerID || '-'}</code></td>
+ <td>${router.Addresses ? router.Addresses.join('<br>') : '-'}</td>
+ <td>${router.ExpiresAt || '-'}</td>
+ </tr>
+ `).join('');
+}
+
+async function actionRequest(url, method = 'POST', body = null) {
+ try {
+ const options = {
+ method,
+ headers: getAuthHeaders()
+ };
+ if (body) {
+ options.headers['Content-Type'] = 'application/json';
+ options.body = JSON.stringify(body);
+ }
+
+ 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';
+ throw new Error('Unauthorized. Please login again.');
+ }
+ if (!response.ok) {
+ throw new Error(`HTTP error! status: ${response.status}`);
+ }
+
+ // Return JSON if present, otherwise just true
+ const contentType = response.headers.get("content-type");
+ if (contentType && contentType.indexOf("application/json") !== -1) {
+ return await response.json();
+ }
+
+ // Refresh data
+ loadData();
+ return true;
+ } catch (error) {
+ alert('Action failed: ' + error.message);
+ throw error;
+ }
+}
+
+function approveEnrollment(id) {
+ if (confirm('Are you sure you want to approve this enrollment?')) {
+ actionRequest(`/api/admin/enrollments/${id}/approve`);
+ }
+}
+
+function rejectEnrollment(id) {
+ if (confirm('Are you sure you want to reject this enrollment?')) {
+ actionRequest(`/api/admin/enrollments/${id}/reject`);
+ }
+}
+
+function revokeDevice(id) {
+ if (confirm('Are you sure you want to revoke this device? This will terminate its connection.')) {
+ actionRequest(`/api/user/revoke?id=${id}`);
+ }
+}
+
+window.logout = function() {
+ localStorage.removeItem('sam_admin_token');
+ window.location.href = '/auth/logout';
+};
+
+function updateUIForRole(role, userId) {
+ // 1. Update Profile Display
+ const profileSpan = document.querySelector('.user-profile span');
+ if (profileSpan) {
+ profileSpan.innerText = role === 'admin' ? 'Admin' : (userId ? userId.substring(0, 15) + '...' : 'User');
+ }
+ const avatarDiv = document.querySelector('.user-profile .avatar');
+ if (avatarDiv) {
+ avatarDiv.innerText = role === 'admin' ? 'A' : 'U';
+ }
+
+ // 2. Hide/Show Navigation Options
+ const navItems = document.querySelectorAll('.nav-item');
+ navItems.forEach(item => {
+ const target = item.getAttribute('data-target');
+ if (target === 'users' || target === 'enrollments' || target === 'policy') {
+ if (role === 'admin') {
+ item.style.display = 'flex';
+ } else {
+ item.style.display = 'none';
+ if (item.classList.contains('active')) {
+ switchTab('overview');
+ }
+ }
+ }
+ });
+
+ // 3. Hide/Show Form Owner ID input
+ const ownerInput = document.getElementById('token-owner');
+ 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
+ }
+ }
+ }
+
+ // 4. Hide users/pending sections from stats grid for normal users
+ const usersCard = document.getElementById('stat-users').closest('.stat-card');
+ const pendingCard = document.getElementById('stat-pending').closest('.stat-card');
+ if (usersCard && pendingCard) {
+ if (role === 'admin') {
+ usersCard.style.display = 'block';
+ pendingCard.style.display = 'block';
+ } else {
+ usersCard.style.display = 'none';
+ pendingCard.style.display = 'none';
+ }
+ }
+}
+
+function switchTab(target) {
+ const navItems = document.querySelectorAll('.nav-item');
+ const viewSections = document.querySelectorAll('.view-section');
+ 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');
+
+ const activeView = document.getElementById(`view-${target}`);
+ if (activeView) activeView.classList.add('active');
+}
+
+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 => {
+ const conns = r.ConnectedPeers || [];
+ const dhtSize = r.DHTSize || 0;
+
+ // Calculate remaining lease time in seconds
+ let elapsed = 0;
+ if (r.ExpiresAt) {
+ elapsed = Math.max(0, Math.floor((new Date(r.ExpiresAt) - new Date()) / 1000));
+ }
+
+ 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('');
+
+ topoList.innerHTML += `
+ <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="badge badge-approved">Lease: ${elapsed}s</span>
+ </div>
+ <div class="router-metrics">
+ <div class="router-metric-item">
+ <div class="router-metric-val">${conns.length}</div>
+ <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 style="font-size: 0.7rem; color: var(--text-secondary)">DHT Size</div>
+ </div>
+ </div>
+ <div style="font-size: 0.8rem; font-weight: 600; color: var(--text-secondary)">Connected Peers:</div>
+ <ul class="router-peers-list">${peersHTML}</ul>
+ </div>
+ `;
+ });
+}
+
+function renderBootstrapTokensTable(tokens) {
+ const tbody = document.getElementById('table-bootstrap');
+ if (tokens.length === 0) {
+ tbody.innerHTML = `<tr><td colspan="5" class="text-center">No active bootstrap tokens found</td></tr>`;
+ return;
+ }
+
+ 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>
+ </tr>
+ `;
+ }).join('');
+}
+
+window.generateBootstrapToken = async function() {
+ const role = document.getElementById('token-role').value;
+ const owner_id = document.getElementById('token-owner').value;
+ const max_usages = parseInt(document.getElementById('token-usages').value, 10);
+ const description = document.getElementById('token-desc').value;
+
+ const payload = {
+ role,
+ owner_id,
+ max_usages,
+ description
+ };
+
+ 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.');
+ document.getElementById('form-generate-token').reset();
+ loadData();
+ }
+ } catch (err) {
+ // actionRequest already alerts on failure
+ }
+};
+
+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 = getAuthHeaders();
+ headers['Content-Type'] = 'application/x-protobuf';
+
+ try {
+ const response = await fetch('/api/policies', {
+ method: 'POST',
+ headers: headers,
+ body: pbBytes
+ });
+ if (response.ok) {
+ alert('Mesh policy updated and applied successfully!');
+ loadData();
+ } else {
+ const text = await response.text();
+ alert('Failed to save policy: ' + text);
+ }
+ } catch (err) {
+ alert('Network error: ' + err.message);
+ }
+};
diff --git a/cmd/sam-console/public/index.html b/cmd/sam-console/public/index.html
new file mode 100644
index 00000000..bd4f6e81
--- /dev/null
+++ b/cmd/sam-console/public/index.html
@@ -0,0 +1,299 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>SAM Console</title>
+ <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
+ <link rel="stylesheet" href="style.css">
+</head>
+<body>
+ <!-- Landing Page Overlay -->
+ <div id="landing-page" class="landing-overlay active">
+ <div class="landing-content glass-panel">
+ <div class="logo">
+ <div class="logo-icon"></div>
+ <h2>SAM Mesh</h2>
+ </div>
+ <p class="subtitle">Securely manage your global mesh network.</p>
+
+ <div class="auth-buttons" id="sso-login-group" style="display: none; margin-bottom: 24px;">
+ <p style="text-align: left; font-size: 0.85rem; color: var(--text-secondary); margin-bottom: 8px;">Interactive Single Sign-On</p>
+ <button class="btn btn-primary" onclick="redirectToSSO()" style="width: 100%;">
+ Log In with OIDC (Redirect)
+ </button>
+ <div class="divider" style="margin: 1.5rem 0;"><span>or use manual tokens</span></div>
+ </div>
+
+ <div class="auth-buttons">
+ <p style="text-align: left; font-size: 0.85rem; color: var(--text-secondary); margin-bottom: 8px;">Sign In via OIDC Token</p>
+ <div class="input-group">
+ <input type="password" id="oidc-token-input" placeholder="OIDC JWT Token">
+ </div>
+ <button class="btn btn-primary" onclick="loginOIDC()" style="width: 100%; margin-top: 12px; margin-bottom: 24px;">
+ Sign In with Token
+ </button>
+ </div>
+
+ <div class="divider">
+ <span>Admin</span>
+ </div>
+
+ <div class="admin-login-section">
+ <p>Root Access via Token</p>
+ <div class="input-group">
+ <input type="password" id="admin-token-input" placeholder="Bearer Token">
+ </div>
+ <button class="btn btn-primary" onclick="saveAdminToken()" style="width: 100%; margin-top: 16px;">
+ Login as Admin
+ </button>
+ </div>
+ </div>
+ </div>
+
+ <!-- Main Dashboard Application -->
+ <div class="app-container" id="app-container" style="display: none;">
+ <!-- Sidebar Navigation -->
+ <aside class="sidebar">
+ <div class="sidebar-header">
+ <div class="logo"></div>
+ <h2>SAM Console</h2>
+ </div>
+ <nav class="sidebar-nav">
+ <a href="#" class="nav-item active" data-target="overview">
+ <svg viewBox="0 0 24 24" width="20" height="20" stroke="currentColor" stroke-width="2" fill="none"><rect x="3" y="3" width="7" height="7"></rect><rect x="14" y="3" width="7" height="7"></rect><rect x="14" y="14" width="7" height="7"></rect><rect x="3" y="14" width="7" height="7"></rect></svg>
+ Overview
+ </a>
+ <a href="#" class="nav-item" data-target="users">
+ <svg viewBox="0 0 24 24" width="20" height="20" stroke="currentColor" stroke-width="2" fill="none"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"></path><circle cx="9" cy="7" r="4"></circle><path d="M23 21v-2a4 4 0 0 0-3-3.87"></path><path d="M16 3.13a4 4 0 0 1 0 7.75"></path></svg>
+ Users
+ </a>
+ <a href="#" class="nav-item" data-target="nodes">
+ <svg 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="#" class="nav-item" data-target="enrollments">
+ <svg 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
+ </a>
+ <a href="#" class="nav-item" data-target="routers">
+ <svg viewBox="0 0 24 24" width="20" height="20" stroke="currentColor" stroke-width="2" fill="none"><path d="M2 12h20"></path><path d="M12 2v20"></path><rect x="2" y="2" width="20" height="20" rx="2" ry="2"></rect></svg>
+ Routers
+ </a>
+ <a href="#" class="nav-item" data-target="bootstrap">
+ <svg viewBox="0 0 24 24" width="20" height="20" stroke="currentColor" stroke-width="2" fill="none"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect><path d="M7 11V7a5 5 0 0 1 10 0v4"></path></svg>
+ Bootstrap Tokens
+ </a>
+ <a href="#" class="nav-item" data-target="policy">
+ <svg viewBox="0 0 24 24" width="20" height="20" stroke="currentColor" stroke-width="2" fill="none"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path><polyline points="14 2 14 8 20 8"></polyline><line x1="16" y1="13" x2="8" y2="13"></line><line x1="16" y1="17" x2="8" y2="17"></line><polyline points="10 9 9 9 8 9"></polyline></svg>
+ Mesh Policy
+ </a>
+ </nav>
+ </aside>
+
+ <!-- Main Content Area -->
+ <main class="main-content">
+ <header class="topbar">
+ <div class="search-bar">
+ <svg viewBox="0 0 24 24" width="18" height="18" stroke="currentColor" stroke-width="2" fill="none"><circle cx="11" cy="11" r="8"></circle><line x1="21" y1="21" x2="16.65" y2="16.65"></line></svg>
+ <input type="text" placeholder="Search resources...">
+ </div>
+ <div class="user-profile">
+ <div class="avatar">A</div>
+ <span>Admin</span>
+ <button class="btn btn-sm btn-secondary" onclick="logout()" style="margin-left: 12px; padding: 4px 8px; font-size: 0.8rem; background: var(--border-color); border: 1px solid var(--border-color);">Logout</button>
+ </div>
+ </header>
+
+ <div class="content-scroll">
+ <!-- Overview View -->
+ <section id="view-overview" class="view-section active">
+ <div class="header-banner">
+ <h1>Network Overview</h1>
+ <p>Real-time statistics for your zero-trust mesh.</p>
+ <button class="btn btn-primary" onclick="loadData()">
+ <svg viewBox="0 0 24 24" width="16" height="16" stroke="currentColor" stroke-width="2" fill="none"><polyline points="23 4 23 10 17 10"></polyline><path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"></path></svg>
+ Refresh
+ </button>
+ </div>
+
+ <div class="stats-grid">
+ <div class="stat-card">
+ <div class="stat-title">Active Users</div>
+ <div class="stat-value" id="stat-users">0</div>
+ </div>
+ <div class="stat-card">
+ <div class="stat-title">Enrolled Nodes</div>
+ <div class="stat-value" id="stat-nodes">0</div>
+ </div>
+ <div class="stat-card">
+ <div class="stat-title">Active Routers</div>
+ <div class="stat-value" id="stat-routers">0</div>
+ </div>
+ <div class="stat-card">
+ <div class="stat-title">Pending Enrollments</div>
+ <div class="stat-value" id="stat-pending">0</div>
+ </div>
+ </div>
+
+ <div class="section-header" style="margin-top: 2rem;">
+ <h2>Network Topography</h2>
+ </div>
+ <div id="router-topography-list" class="router-cards-grid">
+ <div class="text-center" style="grid-column: 1/-1; padding: 2rem; color: var(--text-secondary);">Loading topography...</div>
+ </div>
+ </section>
+
+ <!-- Users View -->
+ <section id="view-users" class="view-section">
+ <div class="section-header">
+ <h2>Users</h2>
+ </div>
+ <div class="card">
+ <table class="data-table">
+ <thead>
+ <tr>
+ <th>ID</th>
+ <th>Subject (OIDC)</th>
+ <th>Name</th>
+ <th>Email</th>
+ </tr>
+ </thead>
+ <tbody id="table-users">
+ <tr><td colspan="4" class="text-center">Loading...</td></tr>
+ </tbody>
+ </table>
+ </div>
+ </section>
+
+ <!-- Nodes View -->
+ <section id="view-nodes" class="view-section">
+ <div class="section-header">
+ <h2>Enrolled Nodes</h2>
+ </div>
+ <div class="card">
+ <table class="data-table">
+ <thead>
+ <tr>
+ <th>Node ID</th>
+ <th>Type</th>
+ <th>Owner</th>
+ <th>Actions</th>
+ </tr>
+ </thead>
+ <tbody id="table-nodes">
+ <tr><td colspan="4" class="text-center">Loading...</td></tr>
+ </tbody>
+ </table>
+ </div>
+ </section>
+
+ <!-- Enrollments View -->
+ <section id="view-enrollments" class="view-section">
+ <div class="section-header">
+ <h2>Enrollment Requests</h2>
+ </div>
+ <div class="card">
+ <table class="data-table">
+ <thead>
+ <tr>
+ <th>Request ID</th>
+ <th>Status</th>
+ <th>Created At</th>
+ <th>Actions</th>
+ </tr>
+ </thead>
+ <tbody id="table-enrollments">
+ <tr><td colspan="4" class="text-center">Loading...</td></tr>
+ </tbody>
+ </table>
+ </div>
+ </section>
+
+ <!-- Routers View -->
+ <section id="view-routers" class="view-section">
+ <div class="section-header">
+ <h2>Active Routers (Leases)</h2>
+ </div>
+ <div class="card">
+ <table class="data-table">
+ <thead>
+ <tr>
+ <th>Router ID</th>
+ <th>Endpoint</th>
+ <th>Lease Expires</th>
+ </tr>
+ </thead>
+ <tbody id="table-routers">
+ <tr><td colspan="3" class="text-center">Loading...</td></tr>
+ </tbody>
+ </table>
+ </div>
+ </section>
+
+ <!-- Bootstrap Tokens View -->
+ <section id="view-bootstrap" class="view-section">
+ <div class="section-header">
+ <h2>Bootstrap Tokens</h2>
+ </div>
+ <div class="card" style="margin-bottom: 2rem; padding: 2rem;">
+ <h3>Generate Bootstrap Token</h3>
+ <form id="form-generate-token" onsubmit="event.preventDefault(); generateBootstrapToken();" style="display: grid; gap: 1rem; max-width: 500px; margin-top: 1rem;">
+ <div class="input-group" style="display: flex; flex-direction: column; gap: 4px;">
+ <label for="token-role" style="font-size: 0.85rem; color: var(--text-secondary);">Role</label>
+ <select id="token-role" class="form-control" style="background: rgba(0,0,0,0.2); border: 1px solid var(--border-color); color: var(--text-primary); border-radius: 4px; padding: 8px;">
+ <option value="sam:role:node">Node (sam:role:node)</option>
+ <option value="sam:role:router">Router (sam:role:router)</option>
+ <option value="sam:role:sambox">Box (sam:role:sambox)</option>
+ </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>
+ </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>
+ <input type="number" id="token-usages" value="1" min="1" style="background: rgba(0,0,0,0.2); border: 1px solid var(--border-color); color: var(--text-primary); border-radius: 4px; padding: 8px;" required>
+ </div>
+ <div class="input-group" style="display: flex; flex-direction: column; gap: 4px;">
+ <label for="token-desc" style="font-size: 0.85rem; color: var(--text-secondary);">Description</label>
+ <input type="text" id="token-desc" placeholder="Token purpose" style="background: rgba(0,0,0,0.2); border: 1px solid var(--border-color); color: var(--text-primary); border-radius: 4px; padding: 8px;">
+ </div>
+ <button type="submit" class="btn btn-primary" style="margin-top: 12px; max-width: 200px;">Generate Token</button>
+ </form>
+ </div>
+ <div class="card">
+ <h3>Active Tokens</h3>
+ <table class="data-table">
+ <thead>
+ <tr>
+ <th>ID</th>
+ <th>Role</th>
+ <th>Owner</th>
+ <th>Usages</th>
+ <th>Expires</th>
+ </tr>
+ </thead>
+ <tbody id="table-bootstrap">
+ <tr><td colspan="5" class="text-center">Loading...</td></tr>
+ </tbody>
+ </table>
+ </div>
+ </section>
+
+ <!-- Mesh Policy View -->
+ <section id="view-policy" class="view-section">
+ <div class="section-header">
+ <h2>Mesh Security Policies</h2>
+ </div>
+ <div class="card" style="padding: 2rem;">
+ <textarea id="policy-yaml" style="width: 100%; height: 450px; font-family: monospace; background: rgba(0,0,0,0.2); color: #a5a1b8; border: 1px solid var(--border-color); border-radius: 0.5rem; padding: 1rem; margin-bottom: 1.5rem;" placeholder="# Loading policies..."></textarea>
+ <button class="btn btn-primary" onclick="savePolicy()">Save & Apply Policy</button>
+ </div>
+ </section>
+ </div>
+ </main>
+ </div>
+ <script src="app.js"></script>
+</body>
+</html>
diff --git a/cmd/sam-console/public/style.css b/cmd/sam-console/public/style.css
new file mode 100644
index 00000000..9a898812
--- /dev/null
+++ b/cmd/sam-console/public/style.css
@@ -0,0 +1,566 @@
+:root {
+ --bg-dark: #0f172a;
+ --bg-surface: #1e293b;
+ --bg-card: rgba(30, 41, 59, 0.7);
+ --border-color: rgba(255, 255, 255, 0.1);
+ --text-primary: #f8fafc;
+ --text-secondary: #94a3b8;
+ --accent: #3b82f6;
+ --accent-hover: #2563eb;
+ --success: #10b981;
+ --danger: #ef4444;
+}
+
+* {
+ margin: 0;
+ padding: 0;
+ box-sizing: border-box;
+}
+
+body {
+ font-family: 'Inter', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
+ background-color: var(--bg-dark);
+ color: var(--text-primary);
+ line-height: 1.5;
+ height: 100vh;
+ overflow: hidden;
+}
+
+/* Layout */
+.app-container {
+ display: flex;
+ height: 100vh;
+ width: 100vw;
+}
+
+/* Sidebar */
+.sidebar {
+ width: 260px;
+ background-color: var(--bg-surface);
+ border-right: 1px solid var(--border-color);
+ display: flex;
+ flex-direction: column;
+}
+
+.sidebar-header {
+ height: 70px;
+ display: flex;
+ align-items: center;
+ padding: 0 24px;
+ border-bottom: 1px solid var(--border-color);
+}
+
+.sidebar-header .logo {
+ width: 32px;
+ height: 32px;
+ background: linear-gradient(135deg, #3b82f6 0%, #8b5cf6 100%);
+ border-radius: 8px;
+ margin-right: 12px;
+}
+
+.sidebar-header h2 {
+ font-size: 1.1rem;
+ font-weight: 600;
+ letter-spacing: 0.5px;
+}
+
+.sidebar-nav {
+ padding: 20px 12px;
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+}
+
+.nav-item {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ padding: 12px 16px;
+ color: var(--text-secondary);
+ text-decoration: none;
+ border-radius: 8px;
+ font-weight: 500;
+ transition: all 0.2s ease;
+}
+
+.nav-item:hover {
+ background-color: rgba(255, 255, 255, 0.05);
+ color: var(--text-primary);
+}
+
+.nav-item.active {
+ background-color: rgba(59, 130, 246, 0.15);
+ color: var(--accent);
+}
+
+/* Main Content */
+.main-content {
+ flex: 1;
+ display: flex;
+ flex-direction: column;
+ overflow: hidden;
+}
+
+.topbar {
+ height: 70px;
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 0 32px;
+ border-bottom: 1px solid var(--border-color);
+ background-color: rgba(15, 23, 42, 0.8);
+ backdrop-filter: blur(12px);
+}
+
+.search-bar {
+ display: flex;
+ align-items: center;
+ background-color: rgba(255, 255, 255, 0.05);
+ border: 1px solid var(--border-color);
+ border-radius: 20px;
+ padding: 8px 16px;
+ width: 300px;
+}
+
+.search-bar input {
+ background: none;
+ border: none;
+ color: var(--text-primary);
+ outline: none;
+ margin-left: 8px;
+ width: 100%;
+}
+
+.search-bar input::placeholder {
+ color: var(--text-secondary);
+}
+
+.user-profile {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+}
+
+.avatar {
+ width: 36px;
+ height: 36px;
+ background-color: var(--accent);
+ border-radius: 50%;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ font-weight: 600;
+}
+
+.content-scroll {
+ flex: 1;
+ overflow-y: auto;
+ padding: 32px;
+}
+
+/* Views */
+.view-section {
+ display: none;
+ animation: fadeIn 0.3s ease;
+}
+
+.view-section.active {
+ display: block;
+}
+
+@keyframes fadeIn {
+ from { opacity: 0; transform: translateY(10px); }
+ to { opacity: 1; transform: translateY(0); }
+}
+
+.header-banner {
+ margin-bottom: 32px;
+ display: flex;
+ align-items: flex-start;
+ justify-content: space-between;
+}
+
+.header-banner h1 {
+ font-size: 2rem;
+ font-weight: 700;
+ margin-bottom: 8px;
+ background: linear-gradient(to right, #f8fafc, #94a3b8);
+ -webkit-background-clip: text;
+ background-clip: text;
+ -webkit-text-fill-color: transparent;
+}
+
+.header-banner p {
+ color: var(--text-secondary);
+}
+
+.section-header {
+ margin-bottom: 24px;
+}
+
+.section-header h2 {
+ font-size: 1.5rem;
+ font-weight: 600;
+}
+
+/* Buttons */
+.btn {
+ display: inline-flex;
+ align-items: center;
+ gap: 8px;
+ padding: 10px 20px;
+ border: none;
+ border-radius: 8px;
+ font-size: 0.95rem;
+ font-weight: 500;
+ cursor: pointer;
+ transition: all 0.2s ease;
+}
+
+.btn-primary {
+ background-color: var(--accent);
+ color: white;
+}
+
+.btn-primary:hover {
+ background-color: var(--accent-hover);
+ transform: translateY(-1px);
+}
+
+.btn-sm {
+ padding: 6px 12px;
+ font-size: 0.85rem;
+}
+
+.btn-success {
+ background-color: rgba(16, 185, 129, 0.2);
+ color: var(--success);
+}
+
+.btn-success:hover {
+ background-color: var(--success);
+ color: white;
+}
+
+.btn-danger {
+ background-color: rgba(239, 68, 68, 0.2);
+ color: var(--danger);
+}
+
+.btn-danger:hover {
+ background-color: var(--danger);
+ color: white;
+}
+
+/* Stats Grid */
+.stats-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
+ gap: 24px;
+ margin-bottom: 32px;
+}
+
+.stat-card {
+ background: var(--bg-card);
+ border: 1px solid var(--border-color);
+ border-radius: 16px;
+ padding: 24px;
+ backdrop-filter: blur(12px);
+ transition: transform 0.2s ease, box-shadow 0.2s ease;
+}
+
+.stat-card:hover {
+ transform: translateY(-4px);
+ box-shadow: 0 12px 24px rgba(0, 0, 0, 0.2);
+}
+
+.stat-title {
+ color: var(--text-secondary);
+ font-size: 0.9rem;
+ font-weight: 500;
+ margin-bottom: 12px;
+}
+
+.stat-value {
+ font-size: 2.5rem;
+ font-weight: 700;
+ color: var(--text-primary);
+}
+
+/* Cards & Tables */
+.card {
+ background: var(--bg-card);
+ border: 1px solid var(--border-color);
+ border-radius: 16px;
+ padding: 24px;
+ backdrop-filter: blur(12px);
+}
+
+.data-table {
+ width: 100%;
+ border-collapse: collapse;
+}
+
+.data-table th {
+ text-align: left;
+ padding: 16px;
+ color: var(--text-secondary);
+ font-weight: 500;
+ font-size: 0.9rem;
+ border-bottom: 1px solid var(--border-color);
+}
+
+.data-table td {
+ padding: 16px;
+ border-bottom: 1px solid rgba(255, 255, 255, 0.05);
+ color: var(--text-primary);
+}
+
+.data-table tbody tr {
+ transition: background-color 0.2s ease;
+}
+
+.data-table tbody tr:hover {
+ background-color: rgba(255, 255, 255, 0.02);
+}
+
+.data-table tbody tr:last-child td {
+ border-bottom: none;
+}
+
+.text-center {
+ text-align: center;
+}
+
+.badge {
+ padding: 4px 10px;
+ border-radius: 12px;
+ font-size: 0.8rem;
+ font-weight: 500;
+}
+
+.badge-pending {
+ background-color: rgba(245, 158, 11, 0.2);
+ color: #fbd38d;
+}
+
+.badge-approved {
+ background-color: rgba(16, 185, 129, 0.2);
+ color: #6ee7b7;
+}
+
+.badge-rejected {
+ background-color: rgba(239, 68, 68, 0.2);
+ color: #fca5a5;
+}
+
+.actions-cell {
+ display: flex;
+ gap: 8px;
+}
+
+/* Modal */
+.modal {
+ display: none;
+ position: fixed;
+ top: 0; left: 0; right: 0; bottom: 0;
+ background-color: rgba(0, 0, 0, 0.5);
+ backdrop-filter: blur(8px);
+ z-index: 1000;
+ align-items: center;
+ justify-content: center;
+}
+
+.modal.active {
+ display: flex;
+}
+
+.modal-content {
+ background: var(--bg-surface);
+ border: 1px solid var(--border-color);
+ border-radius: 16px;
+ width: 400px;
+ padding: 32px;
+ box-shadow: 0 24px 48px rgba(0, 0, 0, 0.4);
+}
+
+.modal-header h2 {
+ font-size: 1.5rem;
+ margin-bottom: 16px;
+}
+
+.modal-body p {
+ color: var(--text-secondary);
+ margin-bottom: 24px;
+}
+
+.input-group input {
+ width: 100%;
+ padding: 12px 16px;
+ background: rgba(0, 0, 0, 0.2);
+ border: 1px solid var(--border-color);
+ border-radius: 8px;
+ color: var(--text-primary);
+ font-size: 1rem;
+ outline: none;
+}
+
+.input-group input:focus {
+ border-color: var(--accent);
+}
+
+/* Landing Page Styles */
+.landing-overlay {
+ position: fixed;
+ top: 0; left: 0; right: 0; bottom: 0;
+ background: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%"><defs><radialGradient id="grad1" cx="50%" cy="50%" r="50%" fx="50%" fy="50%"><stop offset="0%" style="stop-color:rgb(24,20,55);stop-opacity:1" /><stop offset="100%" style="stop-color:rgb(7,6,20);stop-opacity:1" /></radialGradient></defs><rect width="100%" height="100%" fill="url(%23grad1)" /></svg>') no-repeat center center fixed;
+ background-size: cover;
+ z-index: 2000;
+ display: none;
+ align-items: center;
+ justify-content: center;
+}
+
+.landing-overlay.active {
+ display: flex;
+}
+
+.landing-content {
+ background: var(--bg-card);
+ backdrop-filter: blur(20px);
+ border: 1px solid var(--border-color);
+ border-radius: 1rem;
+ padding: 3rem;
+ width: 100%;
+ max-width: 400px;
+ text-align: center;
+ box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.5);
+}
+
+.landing-content .logo {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ gap: 1rem;
+ margin-bottom: 1rem;
+}
+
+.landing-content .logo h2 {
+ font-size: 2rem;
+ margin: 0;
+}
+
+.landing-content .subtitle {
+ color: var(--text-secondary);
+ margin-bottom: 2rem;
+}
+
+.divider {
+ display: flex;
+ align-items: center;
+ text-align: center;
+ margin: 2rem 0;
+ color: var(--text-muted);
+ font-size: 0.875rem;
+}
+
+.divider::before, .divider::after {
+ content: '';
+ flex: 1;
+ border-bottom: 1px solid var(--border-color);
+}
+
+.divider span {
+ padding: 0 1rem;
+}
+
+.admin-login-section {
+ background: rgba(0, 0, 0, 0.2);
+ border-radius: 0.5rem;
+ padding: 1.5rem;
+ text-align: left;
+}
+
+.admin-login-section p {
+ margin-top: 0;
+ margin-bottom: 1rem;
+ color: var(--text-secondary);
+ font-size: 0.875rem;
+}
+
+/* Network Topography */
+.router-cards-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(300px, 1-fraction));
+ /* Wait, 1-fraction is a typo in grid, it should be 1fr */
+ grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
+ gap: 20px;
+ margin-top: 20px;
+}
+
+.router-item-card {
+ background: var(--bg-card);
+ border: 1px solid var(--border-color);
+ border-radius: 12px;
+ padding: 20px;
+ display: flex;
+ flex-direction: column;
+ gap: 15px;
+ backdrop-filter: blur(12px);
+}
+
+.router-header {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+}
+
+.router-peer-id {
+ font-family: monospace;
+ font-weight: 600;
+ color: var(--text-primary);
+ font-size: 0.95rem;
+}
+
+.router-metrics {
+ display: flex;
+ background: rgba(0, 0, 0, 0.2);
+ border-radius: 8px;
+ padding: 10px 0;
+}
+
+.router-metric-item {
+ flex: 1;
+ text-align: center;
+}
+
+.router-metric-val {
+ font-size: 1.5rem;
+ font-weight: 700;
+ color: var(--text-primary);
+}
+
+.router-peers-list {
+ margin: 0;
+ padding-left: 20px;
+ color: var(--text-secondary);
+ font-size: 0.85rem;
+ font-family: monospace;
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+}
+
+.form-control {
+ width: 100%;
+ padding: 8px 12px;
+ background: rgba(0,0,0,0.2);
+ border: 1px solid var(--border-color);
+ color: var(--text-primary);
+ border-radius: 4px;
+ outline: none;
+}
+
+.form-control:focus {
+ border-color: var(--accent);
+}
diff --git a/development/kind/10-control-plane.yaml b/development/kind/10-control-plane.yaml
index 65533a42..5938a8ef 100644
--- a/development/kind/10-control-plane.yaml
+++ b/development/kind/10-control-plane.yaml
@@ -88,10 +88,11 @@ spec:
- "--bind-address=0.0.0.0:8080"
- "--db-driver=postgres"
- "--db-dsn=postgres://sam:sam-secret-password@sam-db:5432/sam_mesh?sslmode=disable"
- - "--issuer=${ISSUER}"
- - "--allowed-audiences=sam-mesh-audience,sam-hub-audience"
+ - "--issuer=${CONTROL_PLANE_ISSUERS}"
+ - "--allowed-audiences=${ALLOWED_AUDIENCES}"
- "--policy-file=/etc/sam/policies/policies.yaml"
- "--insecure-skip-tls-verify"
+ - "--admin-token=super-secret-admin-token"
ports:
- { containerPort: 8080, name: http, protocol: TCP }
readinessProbe:
diff --git a/development/kind/12-console.yaml b/development/kind/12-console.yaml
new file mode 100644
index 00000000..ba3dd668
--- /dev/null
+++ b/development/kind/12-console.yaml
@@ -0,0 +1,50 @@
+apiVersion: v1
+kind: Service
+metadata:
+ name: sam-console
+ namespace: ${NAMESPACE}
+spec:
+ type: ClusterIP
+ selector:
+ app: sam-console
+ ports:
+ - { name: http, port: 80, targetPort: 8081, protocol: TCP }
+---
+apiVersion: v1
+kind: Service
+metadata:
+ name: sam-console-nodeport
+ namespace: ${NAMESPACE}
+spec:
+ type: NodePort
+ selector:
+ app: sam-console
+ ports:
+ - { name: http, port: 8081, targetPort: 8081, nodePort: 30081, protocol: TCP }
+---
+apiVersion: apps/v1
+kind: Deployment
+metadata:
+ name: sam-console
+ namespace: ${NAMESPACE}
+spec:
+ replicas: 1
+ selector:
+ matchLabels:
+ app: sam-console
+ template:
+ metadata:
+ labels:
+ app: sam-console
+ spec:
+ containers:
+ - name: sam-console
+ image: sam-console:${IMAGE_TAG}
+ imagePullPolicy: IfNotPresent
+ args:
+ - "--hub=http://sam-control-plane:8080"
+ - "--bind-addr=:8081"
+ - "--static-dir=/app/public"
+ - "--admin-token=super-secret-admin-token"
+ ports:
+ - { containerPort: 8081, name: http, protocol: TCP }
diff --git a/development/kind/13-dex.yaml b/development/kind/13-dex.yaml
new file mode 100644
index 00000000..04bc703c
--- /dev/null
+++ b/development/kind/13-dex.yaml
@@ -0,0 +1,75 @@
+apiVersion: v1
+kind: ConfigMap
+metadata:
+ name: dex-config
+ namespace: ${NAMESPACE}
+data:
+ config.yaml: |
+ issuer: http://dex:5556/dex
+ storage:
+ type: memory
+ web:
+ http: 0.0.0.0:5556
+ oauth2:
+ skipApprovalScreen: true
+ staticClients:
+ - id: sam-console
+ redirectURIs:
+ - http://localhost:9092/auth/callback
+ name: 'SAM Console'
+ public: true
+ enablePasswordDB: true
+ staticPasswords:
+ # bcrypt hash for 'password'
+ hash: "$2a$10$TUOgJVdtu0AL6Y6TcNBQXOSjRWRKhIkC0kXDzN9kOkPB4hg2aFPE2"
+ username: admin
+ userID: "0898fa90-3453-4311-8566-020953250212"
+---
+apiVersion: apps/v1
+kind: Deployment
+metadata:
+ name: dex
+ namespace: ${NAMESPACE}
+spec:
+ replicas: 1
+ selector:
+ matchLabels:
+ app: dex
+ template:
+ metadata:
+ labels:
+ app: dex
+ spec:
+ containers:
+ - name: dex
+ image: ghcr.io/dexidp/dex:v2.41.1
+ args:
+ - dex
+ - serve
+ - /etc/dex/cfg/config.yaml
+ ports:
+ - containerPort: 5556
+ name: http
+ volumeMounts:
+ - name: config
+ mountPath: /etc/dex/cfg
+ volumes:
+ - name: config
+ configMap:
+ name: dex-config
+---
+apiVersion: v1
+kind: Service
+metadata:
+ name: dex
+ namespace: ${NAMESPACE}
+spec:
+ type: NodePort
+ selector:
+ app: dex
+ ports:
+ - name: http
+ port: 5556
+ targetPort: 5556
+ nodePort: 30556
diff --git a/development/kind/kind-config.yaml b/development/kind/kind-config.yaml
index e4ebd36b..e679fa67 100644
--- a/development/kind/kind-config.yaml
+++ b/development/kind/kind-config.yaml
@@ -11,6 +11,12 @@ nodes:
- containerPort: 30401
hostPort: 4001
protocol: TCP
+ - containerPort: 30081
+ hostPort: 9092
+ protocol: TCP
+ - containerPort: 30556
+ hostPort: 5556
+ protocol: TCP
- role: worker
labels:
sam-role: hub
diff --git a/development/kind/run.sh b/development/kind/run.sh
index 71e7742c..758ad115 100755
--- a/development/kind/run.sh
+++ b/development/kind/run.sh
@@ -107,20 +107,36 @@ echo "== Creating kind cluster '${CLUSTER}' =="
kind create cluster --name "${CLUSTER}" --config "${SCRIPT_DIR}/kind-config.yaml"
echo "== Building sam images =="
-make docker-build-control-plane docker-build-router docker-build-node
+make docker-build-control-plane docker-build-router docker-build-node docker-build-sam-console
echo "== Loading sam images into kind =="
-kind load docker-image --name "${CLUSTER}" "sam-control-plane:${IMAGE_TAG}" "sam-router:${IMAGE_TAG}" "sam-node:${IMAGE_TAG}"
+kind load docker-image --name "${CLUSTER}" "sam-control-plane:${IMAGE_TAG}" "sam-router:${IMAGE_TAG}" "sam-node:${IMAGE_TAG}" "sam-console:${IMAGE_TAG}"
read_mesh_nodes
# Apply the control plane and router, and wait until they accept connections
ISSUER="$(kubectl --context "${KCTX}" get --raw /.well-known/openid-configuration | jq -r .issuer)"
[[ -n "$ISSUER" ]] || { echo "could not determine cluster OIDC issuer" >&2; exit 1; }
-export NAMESPACE ISSUER IMAGE_TAG
-echo "== Applying control plane and router (issuer: ${ISSUER}) =="
-for f in "${SCRIPT_DIR}"/00-*.yaml "${SCRIPT_DIR}"/10-*.yaml "${SCRIPT_DIR}"/11-*.yaml; do
- envsubst '${NAMESPACE} ${ISSUER} ${IMAGE_TAG}' < "$f" | kubectl --context "${KCTX}" apply -f -
+OIDC_ISSUER="${OIDC_ISSUER:-http://dex:5556/dex}"
+OIDC_CLIENT_ID="${OIDC_CLIENT_ID:-sam-console}"
+OIDC_CLIENT_SECRET="${OIDC_CLIENT_SECRET:-}"
+OIDC_REDIRECT_URL="${OIDC_REDIRECT_URL:-}"
+
+CONTROL_PLANE_ISSUERS="${ISSUER}"
+if [[ -n "${OIDC_ISSUER}" ]]; then
+ CONTROL_PLANE_ISSUERS="${OIDC_ISSUER},${ISSUER}"
+fi
+
+ALLOWED_AUDIENCES="sam-mesh-audience,sam-hub-audience"
+if [[ -n "${OIDC_CLIENT_ID}" ]]; then
+ ALLOWED_AUDIENCES="${OIDC_CLIENT_ID},${ALLOWED_AUDIENCES}"
+fi
+
+export NAMESPACE ISSUER IMAGE_TAG OIDC_ISSUER OIDC_CLIENT_ID OIDC_CLIENT_SECRET OIDC_REDIRECT_URL CONTROL_PLANE_ISSUERS ALLOWED_AUDIENCES
+
+echo "== Applying control plane and router (issuer: ${CONTROL_PLANE_ISSUERS}) =="
+for f in "${SCRIPT_DIR}"/00-*.yaml "${SCRIPT_DIR}"/10-*.yaml "${SCRIPT_DIR}"/11-*.yaml "${SCRIPT_DIR}"/12-*.yaml "${SCRIPT_DIR}"/13-*.yaml; do
+ envsubst '${NAMESPACE} ${ISSUER} ${IMAGE_TAG} ${OIDC_ISSUER} ${OIDC_CLIENT_ID} ${OIDC_CLIENT_SECRET} ${OIDC_REDIRECT_URL} ${CONTROL_PLANE_ISSUERS} ${ALLOWED_AUDIENCES}' < "$f" | kubectl --context "${KCTX}" apply -f -
done
echo "== Waiting for database to be ready =="
@@ -129,6 +145,10 @@ echo "== Waiting for control plane to be ready =="
kubectl --context "${KCTX}" -n "${NAMESPACE}" wait --for=condition=available --timeout=180s deployment/sam-control-plane
echo "== Waiting for router to be ready =="
kubectl --context "${KCTX}" -n "${NAMESPACE}" wait --for=condition=ready --timeout=180s pod -l app=sam-router
+echo "== Waiting for console to be ready =="
+kubectl --context "${KCTX}" -n "${NAMESPACE}" wait --for=condition=available --timeout=180s deployment/sam-console
+echo "== Waiting for Dex to be ready =="
+kubectl --context "${KCTX}" -n "${NAMESPACE}" wait --for=condition=available --timeout=180s deployment/dex
echo "== Applying sam-nodes =="
for line in "${NODE_LINES[@]}"; do
@@ -146,6 +166,9 @@ echo "Mesh up. To call a node's MCP API, port-forward it in another shell, e.g.:
echo " kubectl --context ${KCTX} -n ${NAMESPACE} port-forward deploy/node-a 9091:8080"
echo "then:"
echo " ./bin/mcp-client -url http://127.0.0.1:9091/mcp -token devtoken -tool find_remote_tools -args '{}'"
+echo ""
+echo "You can access the SAM Web Console at:"
+echo " http://localhost:9092/"
if [[ "${1:-}" != "-s" ]]; then
show_cluster_logs
diff --git a/internal/console/server.go b/internal/console/server.go
new file mode 100644
index 00000000..918999fb
--- /dev/null
+++ b/internal/console/server.go
@@ -0,0 +1,292 @@
+package console
+
+import (
+ "context"
+ "crypto/rand"
+ "crypto/sha256"
+ "encoding/base64"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "net/http/httputil"
+ "net/url"
+ "os"
+ "path/filepath"
+
+ "github.com/coreos/go-oidc/v3/oidc"
+ "github.com/google/sam/api"
+ "golang.org/x/oauth2"
+ "google.golang.org/protobuf/proto"
+)
+
+type Config struct {
+ HubURL string
+ AdminToken string
+ StaticDir string
+}
+
+type Server struct {
+ cfg Config
+ mux *http.ServeMux
+ provider *oidc.Provider
+ clientID string
+}
+
+func NewServer(cfg Config) (*Server, error) {
+ if cfg.HubURL == "" {
+ return nil, fmt.Errorf("HubURL is required")
+ }
+
+ hubURL, err := url.Parse(cfg.HubURL)
+ if err != nil {
+ return nil, fmt.Errorf("invalid HubURL: %w", err)
+ }
+
+ var provider *oidc.Provider
+ var clientID string
+
+ resp, err := http.Get(cfg.HubURL + "/info")
+ if err != nil {
+ return nil, fmt.Errorf("failed to query control-plane info for OIDC discovery: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+
+ if resp.StatusCode == http.StatusOK {
+ body, err := io.ReadAll(resp.Body)
+ if err != nil {
+ return nil, fmt.Errorf("failed to read control-plane info body: %w", err)
+ }
+ var info api.HubInfoResponse
+ if err := proto.Unmarshal(body, &info); err != nil {
+ return nil, fmt.Errorf("failed to unmarshal hub info: %w", err)
+ }
+
+ if info.OidcIssuer != "" && info.ClientId != "" {
+ provider, err = oidc.NewProvider(context.Background(), info.OidcIssuer)
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "Warning: failed OIDC discovery on %s: %v\n", info.OidcIssuer, err)
+ } else if provider.Endpoint().AuthURL != "" && provider.Endpoint().TokenURL != "" {
+ clientID = info.ClientId
+ } else {
+ fmt.Fprintf(os.Stderr, "Info: discovered issuer %s does not support authorization flow (M2M only)\n", info.OidcIssuer)
+ provider = nil // Disable console interactive endpoints
+ }
+ }
+ }
+
+ s := &Server{
+ cfg: cfg,
+ mux: http.NewServeMux(),
+ provider: provider,
+ clientID: clientID,
+ }
+
+ // Create reverse proxy to the control plane
+ proxy := &httputil.ReverseProxy{
+ Rewrite: func(r *httputil.ProxyRequest) {
+ r.SetURL(hubURL)
+ r.Out.Host = r.In.Host
+ // If Authorization header is not set, inject from sam_session cookie
+ if r.Out.Header.Get("Authorization") == "" {
+ if cookie, err := r.In.Cookie("sam_session"); err == nil && cookie.Value != "" {
+ r.Out.Header.Set("Authorization", "Bearer "+cookie.Value)
+ }
+ }
+ },
+ }
+
+ // Proxy all API requests to the control plane
+ s.mux.Handle("/api/", http.StripPrefix("/api", proxy))
+
+ // Serve static files
+ fs := http.FileServer(http.Dir(s.cfg.StaticDir))
+ s.mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
+ // Basic check if file exists
+ path := filepath.Join(s.cfg.StaticDir, r.URL.Path)
+ if _, err := os.Stat(path); os.IsNotExist(err) && r.URL.Path != "/" {
+ // SPA fallback: return index.html for unknown paths (useful for flutter/react router)
+ http.ServeFile(w, r, filepath.Join(s.cfg.StaticDir, "index.html"))
+ return
+ }
+ fs.ServeHTTP(w, r)
+ })
+
+ // OIDC login endpoints
+ if s.provider != nil {
+ s.mux.HandleFunc("/auth/login", s.HandleLogin)
+ s.mux.HandleFunc("/auth/callback", s.HandleCallback)
+ s.mux.HandleFunc("/auth/session", s.HandleSession)
+ }
+ s.mux.HandleFunc("/auth/logout", s.HandleLogout)
+ s.mux.HandleFunc("/console/info", s.HandleInfo)
+
+ return s, nil
+}
+
+func (s *Server) Handler() http.Handler {
+ return s.mux
+}
+
+func (s *Server) HandleLogout(w http.ResponseWriter, r *http.Request) {
+ http.SetCookie(w, &http.Cookie{
+ Name: "sam_session",
+ Value: "",
+ Path: "/",
+ MaxAge: -1,
+ })
+ http.Redirect(w, r, "/", http.StatusFound)
+}
+
+func (s *Server) HandleLogin(w http.ResponseWriter, r *http.Request) {
+ scheme := "http"
+ if r.TLS != nil || r.Header.Get("X-Forwarded-Proto") == "https" {
+ scheme = "https"
+ }
+ redirectURI := fmt.Sprintf("%s://%s/auth/callback", scheme, r.Host)
+
+ verifier, challenge, err := generatePKCE()
+ if err != nil {
+ http.Error(w, "Failed to generate PKCE components", http.StatusInternalServerError)
+ return
+ }
+
+ stateBytes := make([]byte, 16)
+ if _, err := rand.Read(stateBytes); err != nil {
+ http.Error(w, "Internal state generator error", http.StatusInternalServerError)
+ return
+ }
+ state := fmt.Sprintf("%x", stateBytes)
+
+ http.SetCookie(w, &http.Cookie{
+ Name: "sam_oidc_state",
+ Value: state,
+ Path: "/",
+ MaxAge: 300,
+ HttpOnly: true,
+ Secure: false,
+ SameSite: http.SameSiteLaxMode,
+ })
+
+ http.SetCookie(w, &http.Cookie{
+ Name: "sam_oidc_verifier",
+ Value: verifier,
+ Path: "/",
+ MaxAge: 300,
+ HttpOnly: true,
+ Secure: false,
+ SameSite: http.SameSiteLaxMode,
+ })
+
+ oauth2Config := &oauth2.Config{
+ ClientID: s.clientID,
+ Endpoint: s.provider.Endpoint(),
+ RedirectURL: redirectURI,
+ Scopes: []string{oidc.ScopeOpenID, "profile", "email"},
+ }
+
+ authURL := oauth2Config.AuthCodeURL(state,
+ oauth2.SetAuthURLParam("code_challenge", challenge),
+ oauth2.SetAuthURLParam("code_challenge_method", "S256"),
+ )
+
+ http.Redirect(w, r, authURL, http.StatusFound)
+}
+
+func (s *Server) HandleCallback(w http.ResponseWriter, r *http.Request) {
+ stateCookie, err := r.Cookie("sam_oidc_state")
+ if err != nil || stateCookie.Value == "" || stateCookie.Value != r.URL.Query().Get("state") {
+ http.Error(w, "Invalid state (CSRF verification failed)", http.StatusBadRequest)
+ return
+ }
+
+ verifierCookie, err := r.Cookie("sam_oidc_verifier")
+ if err != nil || verifierCookie.Value == "" {
+ http.Error(w, "Missing verifier cookie", http.StatusBadRequest)
+ return
+ }
+
+ http.SetCookie(w, &http.Cookie{Name: "sam_oidc_state", Value: "", Path: "/", MaxAge: -1})
+ http.SetCookie(w, &http.Cookie{Name: "sam_oidc_verifier", Value: "", Path: "/", MaxAge: -1})
+
+ code := r.URL.Query().Get("code")
+ if code == "" {
+ http.Error(w, "Missing code parameter", http.StatusBadRequest)
+ return
+ }
+
+ scheme := "http"
+ if r.TLS != nil || r.Header.Get("X-Forwarded-Proto") == "https" {
+ scheme = "https"
+ }
+ redirectURI := fmt.Sprintf("%s://%s/auth/callback", scheme, r.Host)
+
+ oauth2Config := &oauth2.Config{
+ ClientID: s.clientID,
+ Endpoint: s.provider.Endpoint(),
+ RedirectURL: redirectURI,
+ Scopes: []string{oidc.ScopeOpenID, "profile", "email"},
+ }
+
+ oauth2Token, err := oauth2Config.Exchange(r.Context(), code,
+ oauth2.SetAuthURLParam("code_verifier", verifierCookie.Value),
+ )
+ if err != nil {
+ http.Error(w, "Failed to exchange auth code: "+err.Error(), http.StatusInternalServerError)
+ return
+ }
+
+ rawIDToken, ok := oauth2Token.Extra("id_token").(string)
+ if !ok || rawIDToken == "" {
+ http.Error(w, "No id_token field in OAuth2 token response", http.StatusInternalServerError)
+ return
+ }
+
+ http.SetCookie(w, &http.Cookie{
+ Name: "sam_session",
+ Value: rawIDToken,
+ Path: "/",
+ MaxAge: 24 * 3600,
+ HttpOnly: true,
+ Secure: false,
+ SameSite: http.SameSiteLaxMode,
+ })
+
+ http.Redirect(w, r, "/", http.StatusFound)
+}
+
+func (s *Server) HandleSession(w http.ResponseWriter, r *http.Request) {
+ sessionCookie, err := r.Cookie("sam_session")
+ if err != nil || sessionCookie.Value == "" {
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusUnauthorized)
+ _, _ = w.Write([]byte(`{"error": "No active session"}`))
+ return
+ }
+
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusOK)
+ _ = json.NewEncoder(w).Encode(map[string]string{
+ "token": sessionCookie.Value,
+ })
+}
+
+func (s *Server) HandleInfo(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusOK)
+ _ = json.NewEncoder(w).Encode(map[string]any{
+ "oidc_enabled": s.provider != nil,
+ })
+}
+
+func generatePKCE() (string, string, error) {
+ verifierBytes := make([]byte, 32)
+ if _, err := rand.Read(verifierBytes); err != nil {
+ return "", "", err
+ }
+ verifier := base64.RawURLEncoding.EncodeToString(verifierBytes)
+
+ hash := sha256.Sum256([]byte(verifier))
+ challenge := base64.RawURLEncoding.EncodeToString(hash[:])
+ return verifier, challenge, nil
+}
diff --git a/internal/console/server_test.go b/internal/console/server_test.go
new file mode 100644
index 00000000..6f9bdac5
--- /dev/null
+++ b/internal/console/server_test.go
@@ -0,0 +1,98 @@
+package console
+
+import (
+ "crypto/rand"
+ "crypto/rsa"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/google/sam/api"
+ "google.golang.org/protobuf/proto"
+)
+
+func TestNewServer_OIDCAutoDiscovery(t *testing.T) {
+ // 1. Generate a mock RSA key for OIDC signing
+ privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
+ if err != nil {
+ t.Fatalf("failed to generate RSA key: %v", err)
+ }
+
+ // 2. Start mock Hub + OIDC server
+ var serverURL string
+ mux := http.NewServeMux()
+
+ // Mock Control Plane /info endpoint
+ mux.HandleFunc("/info", func(w http.ResponseWriter, r *http.Request) {
+ resp := &api.HubInfoResponse{
+ OidcIssuer: serverURL,
+ ClientId: "mock-console-client",
+ }
+ data, err := proto.Marshal(resp)
+ if err != nil {
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ return
+ }
+ w.Header().Set("Content-Type", "application/x-protobuf")
+ w.WriteHeader(http.StatusOK)
+ _, _ = w.Write(data)
+ })
+
+ // Mock OIDC Discovery endpoint
+ mux.HandleFunc("/.well-known/openid-configuration", func(w http.ResponseWriter, r *http.Request) {
+ cfg := map[string]any{
+ "issuer": serverURL,
+ "authorization_endpoint": serverURL + "/auth",
+ "token_endpoint": serverURL + "/token",
+ "jwks_uri": serverURL + "/keys",
+ }
+ w.Header().Set("Content-Type", "application/json")
+ _ = json.NewEncoder(w).Encode(cfg)
+ })
+
+ // Mock OIDC JWKS keys endpoint
+ mux.HandleFunc("/keys", func(w http.ResponseWriter, r *http.Request) {
+ // Minimum empty JWKS to satisfy client discovery
+ jwks := map[string]any{
+ "keys": []map[string]any{
+ {
+ "kty": "RSA",
+ "alg": "RS256",
+ "use": "sig",
+ "n": privateKey.N.String(),
+ "e": "AQAB",
+ },
+ },
+ }
+ w.Header().Set("Content-Type", "application/json")
+ _ = json.NewEncoder(w).Encode(jwks)
+ })
+
+ mockSrv := httptest.NewServer(mux)
+ defer mockSrv.Close()
+ serverURL = mockSrv.URL
+
+ // 3. Instantiate console Server with auto-discovery flags (empty issuer and client ID)
+ cfg := Config{
+ HubURL: serverURL,
+ AdminToken: "test-admin-token",
+ StaticDir: t.TempDir(),
+ }
+
+ srv, err := NewServer(cfg)
+ if err != nil {
+ t.Fatalf("failed to create server: %v", err)
+ }
+
+ // 4. Verify OIDC parameters were discovered and set
+ if srv.provider == nil {
+ t.Fatal("provider config was not initialized")
+ }
+ if srv.clientID != "mock-console-client" {
+ t.Errorf("expected clientID 'mock-console-client', got '%s'", srv.clientID)
+ }
+ if srv.provider.Endpoint().AuthURL != serverURL+"/auth" {
+ t.Errorf("expected AuthURL '%s', got '%s'", serverURL+"/auth", srv.provider.Endpoint().AuthURL)
+ }
+}
diff --git a/internal/controlplane/server.go b/internal/controlplane/server.go
index b395e8d3..5d2fc0b5 100644
--- a/internal/controlplane/server.go
+++ b/internal/controlplane/server.go
@@ -149,7 +149,9 @@ func (s *Server) Start() error {
mux.HandleFunc("/admin/enrollments/", s.HandleAdminEnrollmentAction)
mux.HandleFunc("/admin/revoke", s.HandleAdminRevoke)
mux.HandleFunc("/admin/status", s.HandleAdminStatus)
- mux.HandleFunc("/admin/", s.HandleAdminUI)
+ mux.HandleFunc("/user/status", s.HandleUserStatus)
+ mux.HandleFunc("/user/bootstrap-tokens", s.HandleUserBootstrapTokens)
+ mux.HandleFunc("/user/revoke", s.HandleUserRevoke)
s.httpServer = &http.Server{
Handler: mux,
@@ -1074,19 +1076,67 @@ func (s *Server) HandleEnrollStatus(w http.ResponseWriter, r *http.Request) {
s.writeEnrollResponse(w, resp)
}
-func (s *Server) checkAdminAuth(w http.ResponseWriter, r *http.Request) bool {
- if s.config.AdminToken == "" {
- http.Error(w, "Unauthorized", http.StatusUnauthorized)
- return false
- }
+func (s *Server) authenticateUser(r *http.Request) (*storage.User, error) {
authHeader := r.Header.Get("Authorization")
if !strings.HasPrefix(authHeader, "Bearer ") {
- http.Error(w, "Unauthorized", http.StatusUnauthorized)
+ return nil, errors.New("missing or invalid authorization header")
+ }
+ tokenStr := strings.TrimPrefix(authHeader, "Bearer ")
+ if tokenStr == "" {
+ return nil, errors.New("empty authorization token")
+ }
+
+ // 1. Check root admin token backdoor
+ if s.config.AdminToken != "" && tokenStr == s.config.AdminToken {
+ return &storage.User{
+ ID: "root-admin",
+ Email: "[email protected]",
+ Role: "admin",
+ CreatedAt: time.Now(),
+ }, nil
+ }
+
+ // 2. Validate OIDC token
+ ctx := r.Context()
+ claims, _, err := identity.VerifyJWT(ctx, tokenStr, s.config.AllowedAudiences, s.getProviders())
+ if err != nil {
+ return nil, fmt.Errorf("failed to verify OIDC token: %w", err)
+ }
+
+ sub, _ := claims["sub"].(string)
+ if sub == "" {
+ return nil, errors.New("token subject (sub) claim is empty")
+ }
+ email, _ := claims["email"].(string)
+
+ // Fetch or auto-register user
+ user, err := s.store.GetUser(ctx, sub)
+ if err == storage.ErrNotFound {
+ user = &storage.User{
+ ID: sub,
+ Email: email,
+ Role: "user",
+ CreatedAt: time.Now(),
+ }
+ if err := s.store.SaveUser(ctx, user); err != nil {
+ return nil, fmt.Errorf("failed to register user: %w", err)
+ }
+ logger.Infow("Auto-registered new OIDC user", "id", sub, "email", email)
+ } else if err != nil {
+ return nil, fmt.Errorf("failed to get user: %w", err)
+ }
+
+ return user, nil
+}
+
+func (s *Server) checkAdminAuth(w http.ResponseWriter, r *http.Request) bool {
+ user, err := s.authenticateUser(r)
+ if err != nil {
+ http.Error(w, "Unauthorized: "+err.Error(), http.StatusUnauthorized)
return false
}
- token := strings.TrimPrefix(authHeader, "Bearer ")
- if token == "" || token != s.config.AdminToken {
- http.Error(w, "Unauthorized", http.StatusUnauthorized)
+ if user.Role != "admin" {
+ http.Error(w, "Forbidden: Admin role required", http.StatusForbidden)
return false
}
return true
@@ -1393,3 +1443,204 @@ func (s *Server) buildApprovedBootstrapEnrollResponse(ctx context.Context, biscu
Expiration: expiration,
}, nil
}
+
+func (s *Server) HandleUserStatus(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodGet {
+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+ user, err := s.authenticateUser(r)
+ if err != nil {
+ http.Error(w, "Unauthorized: "+err.Error(), http.StatusUnauthorized)
+ return
+ }
+
+ ctx := r.Context()
+ routers, err := s.store.GetActiveRouters(ctx)
+ if err != nil {
+ logger.Errorf("Failed to get active routers: %v", err)
+ http.Error(w, "Internal server error", http.StatusInternalServerError)
+ return
+ }
+
+ nodes := []storage.EnrolledNode{}
+ if user.Role == "admin" {
+ nodes, err = s.store.ListNodes(ctx)
+ } else {
+ allNodes, err := s.store.ListNodes(ctx)
+ if err == nil {
+ for _, n := range allNodes {
+ if n.OwnerID == user.ID {
+ nodes = append(nodes, n)
+ }
+ }
+ }
+ }
+ if err != nil {
+ logger.Errorf("Failed to list nodes: %v", err)
+ http.Error(w, "Internal server error", http.StatusInternalServerError)
+ return
+ }
+
+ tokens := []storage.BootstrapToken{}
+ allTokens, err := s.store.ListBootstrapTokens(ctx)
+ if err == nil {
+ for _, t := range allTokens {
+ if t.OwnerID == user.ID || user.Role == "admin" {
+ tokens = append(tokens, t)
+ }
+ }
+ }
+ if err != nil {
+ logger.Errorf("Failed to list bootstrap tokens: %v", err)
+ http.Error(w, "Internal server error", http.StatusInternalServerError)
+ return
+ }
+
+ var policyYAML string
+ policy, err := s.store.GetPolicy(ctx)
+ if err == nil {
+ yamlData, err := yaml.Marshal(policy)
+ if err == nil {
+ policyYAML = string(yamlData)
+ }
+ }
+
+ resp := map[string]any{
+ "user": map[string]any{
+ "id": user.ID,
+ "email": user.Email,
+ "role": user.Role,
+ },
+ "active_routers": routers,
+ "enrolled_nodes": nodes,
+ "bootstrap_tokens": tokens,
+ "policy_yaml": policyYAML,
+ }
+
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusOK)
+ _ = json.NewEncoder(w).Encode(resp)
+}
+
+func (s *Server) HandleUserBootstrapTokens(w http.ResponseWriter, r *http.Request) {
+ user, err := s.authenticateUser(r)
+ if err != nil {
+ http.Error(w, "Unauthorized: "+err.Error(), http.StatusUnauthorized)
+ return
+ }
+
+ if r.Method != http.MethodPost {
+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+
+ var req struct {
+ Role string `json:"role"`
+ TTLHours int `json:"ttl_hours"`
+ MaxUsages int `json:"max_usages"`
+ Description string `json:"description"`
+ }
+
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ http.Error(w, "Invalid JSON body", http.StatusBadRequest)
+ return
+ }
+ defer func() { _ = r.Body.Close() }()
+
+ if req.Role == "" {
+ req.Role = api.RoleNode
+ }
+
+ if user.Role != "admin" && req.Role != api.RoleNode && req.Role != api.RoleSamBox {
+ http.Error(w, "Forbidden: Standard users can only generate tokens for node or box roles", http.StatusForbidden)
+ return
+ }
+
+ if req.TTLHours <= 0 {
+ req.TTLHours = 24
+ }
+ if req.MaxUsages <= 0 {
+ req.MaxUsages = 1
+ }
+
+ randBytes := make([]byte, 16)
+ if _, err := rand.Read(randBytes); err != nil {
+ http.Error(w, "Internal keygen error", http.StatusInternalServerError)
+ return
+ }
+ tokenVal := fmt.Sprintf("sam-bt-%x", randBytes)
+ tokenID := fmt.Sprintf("%x", sha256.Sum256([]byte(tokenVal)))
+
+ tokenRecord := &storage.BootstrapToken{
+ ID: tokenID,
+ TokenHash: tokenID,
+ Role: req.Role,
+ OwnerID: user.ID,
+ MaxUsages: req.MaxUsages,
+ UsagesCount: 0,
+ Description: req.Description,
+ CreatedAt: time.Now(),
+ ExpiresAt: time.Now().Add(time.Duration(req.TTLHours) * time.Hour),
+ }
+
+ if err := s.store.SaveBootstrapToken(r.Context(), tokenRecord); err != nil {
+ logger.Errorf("Failed to save bootstrap token: %v", err)
+ http.Error(w, "Internal server error", http.StatusInternalServerError)
+ return
+ }
+
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusCreated)
+ _ = json.NewEncoder(w).Encode(map[string]any{
+ "id": tokenRecord.ID,
+ "token": tokenVal,
+ "role": tokenRecord.Role,
+ "expires_at": tokenRecord.ExpiresAt.Format(time.RFC3339),
+ })
+}
+
+func (s *Server) HandleUserRevoke(w http.ResponseWriter, r *http.Request) {
+ user, err := s.authenticateUser(r)
+ if err != nil {
+ http.Error(w, "Unauthorized: "+err.Error(), http.StatusUnauthorized)
+ return
+ }
+
+ if r.Method != http.MethodPost {
+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+
+ peerID := r.URL.Query().Get("id")
+ if peerID == "" {
+ http.Error(w, "Missing id parameter", http.StatusBadRequest)
+ return
+ }
+
+ ctx := r.Context()
+ node, err := s.store.GetNode(ctx, peerID)
+ if err == storage.ErrNotFound {
+ http.Error(w, "Node not found", http.StatusNotFound)
+ return
+ }
+ if err != nil {
+ logger.Errorf("Failed to check node owner: %v", err)
+ http.Error(w, "Internal server error", http.StatusInternalServerError)
+ return
+ }
+
+ if node.OwnerID != user.ID && user.Role != "admin" {
+ http.Error(w, "Forbidden: You do not own this node", http.StatusForbidden)
+ return
+ }
+
+ if err := s.store.SetNodeBanned(ctx, peerID, true); err != nil {
+ logger.Errorf("Failed to revoke node: %v", err)
+ http.Error(w, "Internal server error", http.StatusInternalServerError)
+ return
+ }
+
+ w.WriteHeader(http.StatusOK)
+ _, _ = w.Write([]byte("Node revoked successfully"))
+}
diff --git a/internal/controlplane/server_test.go b/internal/controlplane/server_test.go
index caba7ed3..7d561e3e 100644
--- a/internal/controlplane/server_test.go
+++ b/internal/controlplane/server_test.go
@@ -992,21 +992,16 @@ func TestAdminPanelAndUI(t *testing.T) {
t.Error("status response missing bootstrap_tokens")
}
- // 3. Query /admin/ UI page -> should succeed and serve the index.html without auth header
+ // 3. Query /admin/ UI page -> should fail with 404 as it is removed
resp, err = client.Get(baseURL + "/admin/")
if err != nil {
t.Fatalf("GET /admin/ failed: %v", err)
}
- if resp.StatusCode != http.StatusOK {
- t.Errorf("expected 200 status for /admin/ UI page, got: %d", resp.StatusCode)
+ if resp.StatusCode != http.StatusNotFound {
+ t.Errorf("expected 404 status for /admin/ UI page, got: %d", resp.StatusCode)
}
- body, _ := io.ReadAll(resp.Body)
_ = resp.Body.Close()
- if !strings.Contains(string(body), "<title>SAM Control Plane Admin</title>") {
- t.Error("UI page does not contain expected HTML title")
- }
-
// 4. Query /policies without token -> should fail with 401
resp, err = client.Get(baseURL + "/policies")
if err != nil {
@@ -1017,3 +1012,116 @@ func TestAdminPanelAndUI(t *testing.T) {
}
_ = resp.Body.Close()
}
+
+func TestUserStatusAndTenancy(t *testing.T) {
+ issuer, mintToken := startCustomMockOIDC(t)
+ s, store, _ := setupTestServer(t, issuer)
+ defer func() { _ = s.Close() }()
+
+ baseURL := "http://" + s.Addr()
+ client := &http.Client{}
+
+ userA := &storage.User{
+ ID: "user-a-sub",
+ Email: "[email protected]",
+ Role: "user",
+ CreatedAt: time.Now(),
+ }
+ userB := &storage.User{
+ ID: "user-b-sub",
+ Email: "[email protected]",
+ Role: "user",
+ CreatedAt: time.Now(),
+ }
+ errUserA := store.SaveUser(context.Background(), userA)
+ if errUserA != nil {
+ t.Fatalf("SaveUser A failed: %v", errUserA)
+ }
+ errUserB := store.SaveUser(context.Background(), userB)
+ if errUserB != nil {
+ t.Fatalf("SaveUser B failed: %v", errUserB)
+ }
+
+ nodeA := &storage.EnrolledNode{
+ PeerID: "peer-node-a",
+ PublicKey: []byte("pubkey-a"),
+ Biscuit: []byte("dummy-biscuit-a"),
+ Role: "sam:role:node",
+ OwnerID: userA.ID,
+ }
+ nodeB := &storage.EnrolledNode{
+ PeerID: "peer-node-b",
+ PublicKey: []byte("pubkey-b"),
+ Biscuit: []byte("dummy-biscuit-b"),
+ Role: "sam:role:node",
+ OwnerID: userB.ID,
+ }
+ errNodeA := store.EnrollNode(context.Background(), nodeA)
+ if errNodeA != nil {
+ t.Fatalf("EnrollNode A failed: %v", errNodeA)
+ }
+ errNodeB := store.EnrollNode(context.Background(), nodeB)
+ if errNodeB != nil {
+ t.Fatalf("EnrollNode B failed: %v", errNodeB)
+ }
+
+ tokenA := mintToken(map[string]interface{}{
+ "iss": issuer,
+ "sub": userA.ID,
+ "email": userA.Email,
+ "aud": "sam-mesh-audience",
+ })
+
+ req, _ := http.NewRequest("GET", baseURL+"/user/status", nil)
+ req.Header.Set("Authorization", "Bearer "+tokenA)
+ resp, err := client.Do(req)
+ if err != nil {
+ t.Fatalf("GET /user/status failed: %v", err)
+ }
+ if resp.StatusCode != http.StatusOK {
+ t.Fatalf("expected 200, got: %d", resp.StatusCode)
+ }
+
+ var data map[string]interface{}
+ _ = json.NewDecoder(resp.Body).Decode(&data)
+ _ = resp.Body.Close()
+
+ enrolledNodes, ok := data["enrolled_nodes"].([]interface{})
+ if !ok {
+ t.Fatal("enrolled_nodes is not an array")
+ }
+ if len(enrolledNodes) != 1 {
+ t.Fatalf("expected 1 node for User A, got: %d", len(enrolledNodes))
+ }
+ nodeMap := enrolledNodes[0].(map[string]interface{})
+ if nodeMap["PeerID"] != "peer-node-a" {
+ t.Errorf("expected node 'peer-node-a', got: %s", nodeMap["PeerID"])
+ }
+
+ reqRevoke, _ := http.NewRequest("POST", baseURL+"/user/revoke?id=peer-node-b", nil)
+ reqRevoke.Header.Set("Authorization", "Bearer "+tokenA)
+ respRevoke, err := client.Do(reqRevoke)
+ if err != nil {
+ t.Fatalf("POST /user/revoke failed: %v", err)
+ }
+ if respRevoke.StatusCode != http.StatusForbidden {
+ t.Errorf("expected 403 Forbidden for revoking someone else's node, got: %d", respRevoke.StatusCode)
+ }
+ _ = respRevoke.Body.Close()
+
+ reqRevokeSelf, _ := http.NewRequest("POST", baseURL+"/user/revoke?id=peer-node-a", nil)
+ reqRevokeSelf.Header.Set("Authorization", "Bearer "+tokenA)
+ respRevokeSelf, err := client.Do(reqRevokeSelf)
+ if err != nil {
+ t.Fatalf("POST /user/revoke self failed: %v", err)
+ }
+ if respRevokeSelf.StatusCode != http.StatusOK {
+ t.Errorf("expected 200 OK for revoking own node, got: %d", respRevokeSelf.StatusCode)
+ }
+ _ = respRevokeSelf.Body.Close()
+
+ nodeAUpdated, _ := store.GetNode(context.Background(), "peer-node-a")
+ if !nodeAUpdated.Banned {
+ t.Error("expected node A to be banned/revoked in DB")
+ }
+}
diff --git a/internal/storage/sql_store.go b/internal/storage/sql_store.go
index bbff3179..ed2f942e 100644
--- a/internal/storage/sql_store.go
+++ b/internal/storage/sql_store.go
@@ -201,6 +201,29 @@ var migrations = []migration{
`ALTER TABLE routers ADD COLUMN dht_size INTEGER`,
},
},
+ {
+ version: 3,
+ postgres: []string{
+ `CREATE TABLE IF NOT EXISTS users (
+ id VARCHAR(255) PRIMARY KEY,
+ email VARCHAR(255) NOT NULL,
+ role VARCHAR(64) NOT NULL,
+ created_at BIGINT NOT NULL
+ )`,
+ `ALTER TABLE nodes ADD COLUMN owner_id VARCHAR(255) REFERENCES users(id)`,
+ `ALTER TABLE bootstrap_tokens ADD COLUMN owner_id VARCHAR(255) REFERENCES users(id)`,
+ },
+ sqlite: []string{
+ `CREATE TABLE IF NOT EXISTS users (
+ id TEXT PRIMARY KEY,
+ email TEXT NOT NULL,
+ role TEXT NOT NULL,
+ created_at BIGINT NOT NULL
+ )`,
+ `ALTER TABLE nodes ADD COLUMN owner_id TEXT REFERENCES users(id)`,
+ `ALTER TABLE bootstrap_tokens ADD COLUMN owner_id TEXT REFERENCES users(id)`,
+ },
+ },
}
func (s *SQLStore) initSchema() error {
@@ -365,18 +388,19 @@ func (s *SQLStore) EnrollNode(ctx context.Context, node *EnrolledNode) error {
var query string
if s.isPostgres() {
query = s.rebind(`
- INSERT INTO nodes (peer_id, public_key, biscuit_token, role, enrollment_type, claims_json, enrolled_at, expires_at, banned)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, FALSE)
+ INSERT INTO nodes (peer_id, public_key, biscuit_token, role, enrollment_type, claims_json, owner_id, enrolled_at, expires_at, banned)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, FALSE)
ON CONFLICT (peer_id)
- DO UPDATE SET public_key = EXCLUDED.public_key, biscuit_token = EXCLUDED.biscuit_token, role = EXCLUDED.role, enrollment_type = EXCLUDED.enrollment_type, claims_json = EXCLUDED.claims_json, enrolled_at = EXCLUDED.enrolled_at, expires_at = EXCLUDED.expires_at`)
+ DO UPDATE SET public_key = EXCLUDED.public_key, biscuit_token = EXCLUDED.biscuit_token, role = EXCLUDED.role, enrollment_type = EXCLUDED.enrollment_type, claims_json = EXCLUDED.claims_json, owner_id = EXCLUDED.owner_id, enrolled_at = EXCLUDED.enrolled_at, expires_at = EXCLUDED.expires_at`)
} else {
query = s.rebind(`
- INSERT INTO nodes (peer_id, public_key, biscuit_token, role, enrollment_type, claims_json, enrolled_at, expires_at, banned)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0)
+ INSERT INTO nodes (peer_id, public_key, biscuit_token, role, enrollment_type, claims_json, owner_id, enrolled_at, expires_at, banned)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 0)
ON CONFLICT (peer_id)
- DO UPDATE SET public_key = excluded.public_key, biscuit_token = excluded.biscuit_token, role = excluded.role, enrollment_type = excluded.enrollment_type, claims_json = excluded.claims_json, enrolled_at = excluded.enrolled_at, expires_at = excluded.expires_at`)
+ DO UPDATE SET public_key = excluded.public_key, biscuit_token = excluded.biscuit_token, role = excluded.role, enrollment_type = excluded.enrollment_type, claims_json = excluded.claims_json, owner_id = excluded.owner_id, enrolled_at = excluded.enrolled_at, expires_at = excluded.expires_at`)
}
+ ownerIDNull := sql.NullString{String: node.OwnerID, Valid: node.OwnerID != ""}
_, err := s.db.ExecContext(ctx, query,
node.PeerID,
node.PublicKey,
@@ -384,6 +408,7 @@ func (s *SQLStore) EnrollNode(ctx context.Context, node *EnrolledNode) error {
node.Role,
node.EnrollmentType,
node.ClaimsJSON,
+ ownerIDNull,
node.EnrolledAt.UnixMilli(),
node.ExpiresAt.UnixMilli(),
)
@@ -392,8 +417,9 @@ func (s *SQLStore) EnrollNode(ctx context.Context, node *EnrolledNode) error {
// GetNode implements Store.
func (s *SQLStore) GetNode(ctx context.Context, peerID string) (*EnrolledNode, error) {
- query := s.rebind(`SELECT peer_id, public_key, biscuit_token, role, enrollment_type, claims_json, enrolled_at, expires_at, banned FROM nodes WHERE peer_id = ?`)
+ query := s.rebind(`SELECT peer_id, public_key, biscuit_token, role, enrollment_type, claims_json, owner_id, enrolled_at, expires_at, banned FROM nodes WHERE peer_id = ?`)
var node EnrolledNode
+ var claimsJSON, ownerID sql.NullString
var enrolledAtUnix, expiresAtUnix int64
err := s.db.QueryRowContext(ctx, query, peerID).Scan(
&node.PeerID,
@@ -401,11 +427,18 @@ func (s *SQLStore) GetNode(ctx context.Context, peerID string) (*EnrolledNode, e
&node.Biscuit,
&node.Role,
&node.EnrollmentType,
- &node.ClaimsJSON,
+ &claimsJSON,
+ &ownerID,
&enrolledAtUnix,
&expiresAtUnix,
&node.Banned,
)
+ if claimsJSON.Valid {
+ node.ClaimsJSON = claimsJSON.String
+ }
+ if ownerID.Valid {
+ node.OwnerID = ownerID.String
+ }
if err == sql.ErrNoRows {
return nil, ErrNotFound
}
@@ -552,34 +585,44 @@ func (s *SQLStore) GetPolicy(ctx context.Context) (*api.PolicyConfig, error) {
// SaveBootstrapToken persists a new bootstrap token.
func (s *SQLStore) SaveBootstrapToken(ctx context.Context, token *BootstrapToken) error {
- query := `INSERT INTO bootstrap_tokens (id, token_hash, role, max_usages, usages_count, description, created_at, expires_at)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?)`
- _, err := s.db.ExecContext(ctx, s.rebind(query),
+ var query string
+ if s.isPostgres() {
+ query = s.rebind(`
+ INSERT INTO bootstrap_tokens (id, token_hash, role, owner_id, max_usages, usages_count, description, created_at, expires_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
+ ON CONFLICT (id) DO NOTHING`)
+ } else {
+ query = s.rebind(`
+ INSERT INTO bootstrap_tokens (id, token_hash, role, owner_id, max_usages, usages_count, description, created_at, expires_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
+ ON CONFLICT (id) DO NOTHING`)
+ }
+ ownerIDNull := sql.NullString{String: token.OwnerID, Valid: token.OwnerID != ""}
+ _, err := s.db.ExecContext(ctx, query,
token.ID,
token.TokenHash,
token.Role,
+ ownerIDNull,
token.MaxUsages,
token.UsagesCount,
token.Description,
token.CreatedAt.Unix(),
token.ExpiresAt.Unix(),
)
- if err != nil {
- return fmt.Errorf("failed to save bootstrap token: %w", err)
- }
- return nil
+ return err
}
-// GetBootstrapToken retrieves a bootstrap token by its ID.
+// GetBootstrapToken retrieves a bootstrap token by its ID (sha256 hash).
func (s *SQLStore) GetBootstrapToken(ctx context.Context, id string) (*BootstrapToken, error) {
- query := `SELECT id, token_hash, role, max_usages, usages_count, description, created_at, expires_at
- FROM bootstrap_tokens WHERE id = ?`
- var created, expires int64
+ query := s.rebind(`SELECT id, token_hash, role, owner_id, max_usages, usages_count, description, created_at, expires_at FROM bootstrap_tokens WHERE id = ?`)
var t BootstrapToken
- err := s.db.QueryRowContext(ctx, s.rebind(query), id).Scan(
+ var created, expires int64
+ var ownerID sql.NullString
+ err := s.db.QueryRowContext(ctx, query, id).Scan(
&t.ID,
&t.TokenHash,
&t.Role,
+ &ownerID,
&t.MaxUsages,
&t.UsagesCount,
&t.Description,
@@ -588,8 +631,12 @@ func (s *SQLStore) GetBootstrapToken(ctx context.Context, id string) (*Bootstrap
)
if err == sql.ErrNoRows {
return nil, ErrNotFound
- } else if err != nil {
- return nil, fmt.Errorf("failed to scan bootstrap token: %w", err)
+ }
+ if err != nil {
+ return nil, err
+ }
+ if ownerID.Valid {
+ t.OwnerID = ownerID.String
}
t.CreatedAt = time.Unix(created, 0)
t.ExpiresAt = time.Unix(expires, 0)
@@ -723,7 +770,7 @@ func (s *SQLStore) UpdateEnrollmentRequest(ctx context.Context, id string, statu
// ListNodes retrieves all enrolled nodes.
func (s *SQLStore) ListNodes(ctx context.Context) ([]EnrolledNode, error) {
- query := s.rebind(`SELECT peer_id, public_key, biscuit_token, role, enrollment_type, claims_json, enrolled_at, expires_at, banned FROM nodes ORDER BY enrolled_at DESC`)
+ query := s.rebind(`SELECT peer_id, public_key, biscuit_token, role, enrollment_type, claims_json, owner_id, enrolled_at, expires_at, banned FROM nodes ORDER BY enrolled_at DESC`)
rows, err := s.db.QueryContext(ctx, query)
if err != nil {
return nil, fmt.Errorf("failed to query nodes: %w", err)
@@ -733,7 +780,7 @@ func (s *SQLStore) ListNodes(ctx context.Context) ([]EnrolledNode, error) {
var nodes []EnrolledNode
for rows.Next() {
var node EnrolledNode
- var claimsJSON sql.NullString
+ var claimsJSON, ownerID sql.NullString
var enrolledAtUnix, expiresAtUnix int64
err := rows.Scan(
&node.PeerID,
@@ -742,6 +789,7 @@ func (s *SQLStore) ListNodes(ctx context.Context) ([]EnrolledNode, error) {
&node.Role,
&node.EnrollmentType,
&claimsJSON,
+ &ownerID,
&enrolledAtUnix,
&expiresAtUnix,
&node.Banned,
@@ -752,6 +800,9 @@ func (s *SQLStore) ListNodes(ctx context.Context) ([]EnrolledNode, error) {
if claimsJSON.Valid {
node.ClaimsJSON = claimsJSON.String
}
+ if ownerID.Valid {
+ node.OwnerID = ownerID.String
+ }
node.EnrolledAt = time.UnixMilli(enrolledAtUnix)
node.ExpiresAt = time.UnixMilli(expiresAtUnix)
nodes = append(nodes, node)
@@ -764,7 +815,7 @@ func (s *SQLStore) ListNodes(ctx context.Context) ([]EnrolledNode, error) {
// ListBootstrapTokens retrieves all bootstrap tokens.
func (s *SQLStore) ListBootstrapTokens(ctx context.Context) ([]BootstrapToken, error) {
- query := s.rebind(`SELECT id, token_hash, role, max_usages, usages_count, description, created_at, expires_at FROM bootstrap_tokens ORDER BY created_at DESC`)
+ query := s.rebind(`SELECT id, token_hash, role, owner_id, max_usages, usages_count, description, created_at, expires_at FROM bootstrap_tokens ORDER BY created_at DESC`)
rows, err := s.db.QueryContext(ctx, query)
if err != nil {
return nil, fmt.Errorf("failed to query bootstrap tokens: %w", err)
@@ -775,11 +826,13 @@ func (s *SQLStore) ListBootstrapTokens(ctx context.Context) ([]BootstrapToken, e
for rows.Next() {
var t BootstrapToken
var desc sql.NullString
+ var ownerID sql.NullString
var created, expires int64
err := rows.Scan(
&t.ID,
&t.TokenHash,
&t.Role,
+ &ownerID,
&t.MaxUsages,
&t.UsagesCount,
&desc,
@@ -792,6 +845,9 @@ func (s *SQLStore) ListBootstrapTokens(ctx context.Context) ([]BootstrapToken, e
if desc.Valid {
t.Description = desc.String
}
+ if ownerID.Valid {
+ t.OwnerID = ownerID.String
+ }
t.CreatedAt = time.Unix(created, 0)
t.ExpiresAt = time.Unix(expires, 0)
tokens = append(tokens, t)
@@ -802,6 +858,81 @@ func (s *SQLStore) ListBootstrapTokens(ctx context.Context) ([]BootstrapToken, e
return tokens, nil
}
+// SaveUser creates or updates a user.
+func (s *SQLStore) SaveUser(ctx context.Context, user *User) error {
+ var query string
+ if s.isPostgres() {
+ query = s.rebind(`
+ INSERT INTO users (id, email, role, created_at)
+ VALUES (?, ?, ?, ?)
+ ON CONFLICT (id) DO UPDATE SET email = EXCLUDED.email, role = EXCLUDED.role`)
+ } else {
+ query = s.rebind(`
+ INSERT INTO users (id, email, role, created_at)
+ VALUES (?, ?, ?, ?)
+ ON CONFLICT (id) DO UPDATE SET email = excluded.email, role = excluded.role`)
+ }
+
+ _, err := s.db.ExecContext(ctx, query,
+ user.ID,
+ user.Email,
+ user.Role,
+ user.CreatedAt.Unix(),
+ )
+ return err
+}
+
+// GetUser retrieves a user by ID.
+func (s *SQLStore) GetUser(ctx context.Context, id string) (*User, error) {
+ query := s.rebind(`SELECT id, email, role, created_at FROM users WHERE id = ?`)
+ var user User
+ var created int64
+ err := s.db.QueryRowContext(ctx, query, id).Scan(
+ &user.ID,
+ &user.Email,
+ &user.Role,
+ &created,
+ )
+ if err == sql.ErrNoRows {
+ return nil, ErrNotFound
+ }
+ if err != nil {
+ return nil, err
+ }
+ user.CreatedAt = time.Unix(created, 0)
+ return &user, nil
+}
+
+// ListUsers retrieves all registered users.
+func (s *SQLStore) ListUsers(ctx context.Context) ([]User, error) {
+ query := `SELECT id, email, role, created_at FROM users`
+ rows, err := s.db.QueryContext(ctx, query)
+ if err != nil {
+ return nil, err
+ }
+ defer func() { _ = rows.Close() }()
+
+ var users []User
+ for rows.Next() {
+ var user User
+ var created int64
+ if err := rows.Scan(
+ &user.ID,
+ &user.Email,
+ &user.Role,
+ &created,
+ ); err != nil {
+ return nil, err
+ }
+ user.CreatedAt = time.Unix(created, 0)
+ users = append(users, user)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return users, nil
+}
+
// Close implements Store.
func (s *SQLStore) Close() error {
return s.db.Close()
diff --git a/internal/storage/storage.go b/internal/storage/storage.go
index 6c64c076..0c6c1314 100644
--- a/internal/storage/storage.go
+++ b/internal/storage/storage.go
@@ -44,6 +44,14 @@ type RouterLease struct {
DHTSize int
}
+// User represents a human identity in the mesh.
+type User struct {
+ ID string
+ Email string
+ Role string
+ CreatedAt time.Time
+}
+
// EnrolledNode represents a node enrolled in the mesh.
type EnrolledNode struct {
PeerID string
@@ -52,6 +60,7 @@ type EnrolledNode struct {
Role string
EnrollmentType string
ClaimsJSON string
+ OwnerID string
EnrolledAt time.Time
ExpiresAt time.Time
Banned bool
@@ -62,6 +71,7 @@ type BootstrapToken struct {
ID string
TokenHash string
Role string
+ OwnerID string
MaxUsages int
UsagesCount int
Description string
@@ -96,6 +106,15 @@ type Store interface {
// SaveInitialKey sets the initial key pair if no keys exist yet.
SaveInitialKey(ctx context.Context, priv ed25519.PrivateKey, pub ed25519.PublicKey) error
+ // SaveUser creates or updates a User.
+ SaveUser(ctx context.Context, user *User) error
+
+ // GetUser retrieves a User by ID.
+ GetUser(ctx context.Context, id string) (*User, error)
+
+ // ListUsers retrieves all registered users.
+ ListUsers(ctx context.Context) ([]User, error)
+
// EnrollNode registers or updates a node enrollment.
EnrollNode(ctx context.Context, node *EnrolledNode) error
diff --git a/tests/e2e/console.bats b/tests/e2e/console.bats
new file mode 100644
index 00000000..4dff52df
--- /dev/null
+++ b/tests/e2e/console.bats
@@ -0,0 +1,46 @@
+#!/usr/bin/env bats
+
+load "lib/container_mesh.bash"
+
+setup() {
+ mesh_setup_env
+}
+
+teardown() {
+ mesh_cleanup_env
+}
+
+@test "sam-console starts and proxies to control plane" {
+ run mesh_start_mock_oidc
+ [[ "$status" -eq 0 ]]
+
+ run mesh_start_hub
+ [[ "$status" -eq 0 ]]
+
+ local console_name="${MESH_PREFIX}-console"
+
+ # Admin token used by control plane test setup is "admin-secret-token"
+ docker run -d \
+ --name "${console_name}" \
+ --network "${MESH_NETWORK}" \
+ $(mesh_get_add_hosts) \
+ "sam-console:local" \
+ --hub "http://sam-control-plane:8080" \
+ --bind-addr ":8081" \
+ --admin-token "super-secret-admin-token"
+
+ MESH_CONTAINERS+=("${console_name}")
+
+ # Wait for console to be ready
+ sleep 3
+
+ # Test static index.html is served
+ run docker run --rm --network "${MESH_NETWORK}" curlimages/curl -s "http://${console_name}:8081/"
+ [[ "$status" -eq 0 ]]
+ [[ "$output" == *"SAM Console Loading..."* ]]
+
+ # Test proxy to control plane /admin/status (mapped under /api/)
+ run docker run --rm --network "${MESH_NETWORK}" curlimages/curl -s -f "http://${console_name}:8081/api/admin/status"
+ [[ "$status" -eq 0 ]]
+ [[ "$output" == *"active_routers"* ]]
+}