Skip to content

Agent Mesh

console: embed web assets and mount the console in sam-one

Antonio Ojeaf0a5371b9b25
diff --git a/Dockerfile.sam-console b/Dockerfile.sam-console
index 685ee787..dbe38300 100644
--- a/Dockerfile.sam-console
+++ b/Dockerfile.sam-console
@@ -11,7 +11,7 @@ FROM gcr.io/distroless/static-debian12:nonroot
WORKDIR /app
COPY --from=builder --chown=nonroot:nonroot /bin/sam-console /usr/local/bin/sam-console
-COPY --chown=nonroot:nonroot cmd/sam-console/public /app/public
+COPY --chown=nonroot:nonroot internal/console/public /app/public
USER nonroot:nonroot
EXPOSE 8081
diff --git a/cmd/sam-console/main.go b/cmd/sam-console/main.go
index 94f06fee..b96056a6 100644
--- a/cmd/sam-console/main.go
+++ b/cmd/sam-console/main.go
@@ -33,7 +33,7 @@ func main() {
controlPlaneURL = flag.String("control-plane", "http://localhost:8080", "URL of the SAM control plane")
adminTokenPath = flag.String("admin-token-path", "", "Path to file containing the admin token (or env SAM_ADMIN_TOKEN)")
bindAddr = flag.String("bind-addr", ":8081", "Address to bind the console server")
- staticDir = flag.String("static-dir", "public", "Directory containing static frontend files")
+ staticDir = flag.String("static-dir", "", "Directory containing static frontend files (default: assets embedded in the binary)")
basePath = flag.String("base-path", "", "Base path prefix for the console (e.g. /console)")
externalURL = flag.String("external-url", "", "Origin browsers reach this console on, e.g. https://console.example. Sets the OIDC redirect_uri and cookie Secure flag instead of trusting the Host and X-Forwarded-Proto headers")
)
@@ -51,6 +51,7 @@ func main() {
ControlPlaneURL: *controlPlaneURL,
AdminToken: adminToken,
StaticDir: *staticDir,
+ StaticFS: console.EmbeddedAssets(),
BasePath: console.NormalizeBasePath(*basePath),
ExternalURL: *externalURL,
})
diff --git a/cmd/sam-one/main.go b/cmd/sam-one/main.go
index 4e1c3c9c..2a3d8fa0 100644
--- a/cmd/sam-one/main.go
+++ b/cmd/sam-one/main.go
@@ -141,6 +141,7 @@ func printBanner(srv *standalone.Server, externalURL string) {
fmt.Println("SAM standalone mesh is ready!")
fmt.Println()
fmt.Printf("API URL: %s\n", base)
+ fmt.Printf("Web Console: %s/console\n", base)
fmt.Printf("Router Peer: %s\n", srv.PeerID())
fmt.Printf("Admin Token: %s\n", srv.AdminToken())
fmt.Printf("Join Token: %s\n", srv.JoinToken())
diff --git a/internal/console/embed.go b/internal/console/embed.go
new file mode 100644
index 00000000..92320d85
--- /dev/null
+++ b/internal/console/embed.go
@@ -0,0 +1,35 @@
+// Copyright 2026 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package console
+
+import (
+ "embed"
+ "io/fs"
+)
+
+//go:embed all:public
+var embeddedAssets embed.FS
+
+// EmbeddedAssets returns the compiled-in console frontend, rooted at the
+// asset directory so it can be used directly as Config.StaticFS.
+func EmbeddedAssets() fs.FS {
+ sub, err := fs.Sub(embeddedAssets, "public")
+ if err != nil {
+ // The subtree name is a compile-time constant matching the embed
+ // directive; failure here is unreachable.
+ panic(err)
+ }
+ return sub
+}
diff --git a/cmd/sam-console/public/app.js b/internal/console/public/app.js
similarity index 100%
rename from cmd/sam-console/public/app.js
rename to internal/console/public/app.js
diff --git a/cmd/sam-console/public/index.html b/internal/console/public/index.html
similarity index 100%
rename from cmd/sam-console/public/index.html
rename to internal/console/public/index.html
diff --git a/cmd/sam-console/public/style.css b/internal/console/public/style.css
similarity index 100%
rename from cmd/sam-console/public/style.css
rename to internal/console/public/style.css
diff --git a/cmd/sam-console/public/vendor/js-yaml.LICENSE b/internal/console/public/vendor/js-yaml.LICENSE
similarity index 100%
rename from cmd/sam-console/public/vendor/js-yaml.LICENSE
rename to internal/console/public/vendor/js-yaml.LICENSE
diff --git a/cmd/sam-console/public/vendor/js-yaml.min.js b/internal/console/public/vendor/js-yaml.min.js
similarity index 100%
rename from cmd/sam-console/public/vendor/js-yaml.min.js
rename to internal/console/public/vendor/js-yaml.min.js
diff --git a/internal/console/server.go b/internal/console/server.go
index e601938f..b1d5030a 100644
--- a/internal/console/server.go
+++ b/internal/console/server.go
@@ -22,12 +22,12 @@ import (
"encoding/json"
"fmt"
"io"
+ "io/fs"
"net/http"
"net/http/httputil"
"net/url"
"os"
"path"
- "path/filepath"
"strings"
"time"
@@ -40,8 +40,12 @@ import (
type Config struct {
ControlPlaneURL string
AdminToken string
- StaticDir string
- BasePath string
+ // StaticDir serves frontend assets from disk (live-editable, used by the
+ // ui-dev workflow). It takes precedence over StaticFS.
+ StaticDir string
+ // StaticFS serves frontend assets from an fs.FS, e.g. EmbeddedAssets().
+ StaticFS fs.FS
+ BasePath string
// ExternalURL is the origin browsers reach this console on, e.g.
// "https://console.example". When set it decides the OIDC redirect_uri and
@@ -107,6 +111,16 @@ func NewServer(cfg Config) (*Server, error) {
return nil, fmt.Errorf("ControlPlaneURL is required")
}
+ var assets fs.FS
+ switch {
+ case cfg.StaticDir != "":
+ assets = os.DirFS(cfg.StaticDir)
+ case cfg.StaticFS != nil:
+ assets = cfg.StaticFS
+ default:
+ return nil, fmt.Errorf("static assets are required: set StaticDir or StaticFS")
+ }
+
controlPlaneURL, err := url.Parse(cfg.ControlPlaneURL)
if err != nil {
return nil, fmt.Errorf("invalid ControlPlaneURL: %w", err)
@@ -192,16 +206,18 @@ func NewServer(cfg Config) (*Server, error) {
routes.Handle("/api/", http.StripPrefix("/api", proxy))
// Serve static files
- fs := http.FileServer(http.Dir(s.cfg.StaticDir))
+ fileServer := http.FileServerFS(assets)
routes.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 != "/" {
+ name := strings.TrimPrefix(path.Clean(r.URL.Path), "/")
+ if name == "" {
+ name = "."
+ }
+ if _, err := fs.Stat(assets, name); err != nil && 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"))
+ http.ServeFileFS(w, r, assets, "index.html")
return
}
- fs.ServeHTTP(w, r)
+ fileServer.ServeHTTP(w, r)
})
// OIDC login endpoints
diff --git a/internal/console/server_test.go b/internal/console/server_test.go
index 97c67000..0c42211f 100644
--- a/internal/console/server_test.go
+++ b/internal/console/server_test.go
@@ -19,9 +19,12 @@ import (
"crypto/rand"
"crypto/rsa"
"encoding/json"
+ "io"
"net"
"net/http"
"net/http/httptest"
+ "os"
+ "path/filepath"
"strings"
"sync/atomic"
"testing"
@@ -32,6 +35,101 @@ import (
"google.golang.org/protobuf/proto"
)
+// startNoOIDCControlPlaneStub serves a /info with no issuer, the
+// bootstrap-token-only mode sam-one runs the console in.
+func startNoOIDCControlPlaneStub(t *testing.T) *httptest.Server {
+ t.Helper()
+ mux := http.NewServeMux()
+ mux.HandleFunc("/info", func(w http.ResponseWriter, r *http.Request) {
+ data, err := proto.Marshal(&api.ControlPlaneInfoResponse{})
+ if err != nil {
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ return
+ }
+ w.Header().Set("Content-Type", "application/x-protobuf")
+ _, _ = w.Write(data)
+ })
+ srv := httptest.NewServer(mux)
+ t.Cleanup(srv.Close)
+ return srv
+}
+
+// TestNewServerEmbeddedAssets pins the compiled-in frontend path used by
+// sam-one and the cmd default: StaticFS serving, SPA fallback, StaticDir
+// precedence for live-editing, and the fail-fast when no assets are set.
+func TestNewServerEmbeddedAssets(t *testing.T) {
+ cpStub := startNoOIDCControlPlaneStub(t)
+
+ t.Run("no assets configured", func(t *testing.T) {
+ if _, err := NewServer(Config{ControlPlaneURL: cpStub.URL, AdminToken: "x"}); err == nil {
+ t.Fatal("NewServer without StaticDir or StaticFS should fail")
+ }
+ })
+
+ srv, err := NewServer(Config{
+ ControlPlaneURL: cpStub.URL,
+ AdminToken: "x",
+ StaticFS: EmbeddedAssets(),
+ })
+ if err != nil {
+ t.Fatalf("failed to create server with embedded assets: %v", err)
+ }
+ ts := httptest.NewServer(srv.Handler())
+ defer ts.Close()
+
+ get := func(path string) (int, string) {
+ t.Helper()
+ resp, err := http.Get(ts.URL + path)
+ if err != nil {
+ t.Fatalf("GET %s failed: %v", path, err)
+ }
+ body, err := io.ReadAll(resp.Body)
+ _ = resp.Body.Close()
+ if err != nil {
+ t.Fatalf("failed to read %s body: %v", path, err)
+ }
+ return resp.StatusCode, string(body)
+ }
+
+ if code, body := get("/"); code != http.StatusOK || !strings.Contains(body, "<html") {
+ t.Errorf("GET / = %d, want 200 with the embedded index.html", code)
+ }
+ if code, _ := get("/app.js"); code != http.StatusOK {
+ t.Errorf("GET /app.js = %d, want 200", code)
+ }
+ // SPA fallback: unknown paths serve index.html.
+ if code, body := get("/some/client/route"); code != http.StatusOK || !strings.Contains(body, "<html") {
+ t.Errorf("GET /some/client/route = %d, want 200 with index.html fallback", code)
+ }
+
+ t.Run("StaticDir wins over StaticFS", func(t *testing.T) {
+ dir := t.TempDir()
+ if err := os.WriteFile(filepath.Join(dir, "index.html"), []byte("live-edited marker"), 0o644); err != nil {
+ t.Fatalf("failed to write marker: %v", err)
+ }
+ srv, err := NewServer(Config{
+ ControlPlaneURL: cpStub.URL,
+ AdminToken: "x",
+ StaticDir: dir,
+ StaticFS: EmbeddedAssets(),
+ })
+ if err != nil {
+ t.Fatalf("failed to create server: %v", err)
+ }
+ ts := httptest.NewServer(srv.Handler())
+ defer ts.Close()
+ resp, err := http.Get(ts.URL + "/")
+ if err != nil {
+ t.Fatalf("GET / failed: %v", err)
+ }
+ body, _ := io.ReadAll(resp.Body)
+ _ = resp.Body.Close()
+ if !strings.Contains(string(body), "live-edited marker") {
+ t.Errorf("StaticDir did not take precedence over StaticFS: %q", body)
+ }
+ })
+}
+
func TestNewServer_OIDCAutoDiscovery(t *testing.T) {
// 1. Generate a mock RSA key for OIDC signing
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
diff --git a/internal/standalone/standalone.go b/internal/standalone/standalone.go
index a8a99c98..95c13cda 100644
--- a/internal/standalone/standalone.go
+++ b/internal/standalone/standalone.go
@@ -35,6 +35,7 @@ import (
"time"
"github.com/google/sam/api"
+ "github.com/google/sam/internal/console"
"github.com/google/sam/internal/controlplane"
"github.com/google/sam/internal/router"
"github.com/google/sam/internal/storage"
@@ -53,6 +54,8 @@ const (
adminTokenFile = "admin-token"
routerKeyFile = "router.key"
+ consoleBasePath = "/console"
+
// joinTokenTTL bounds the auto-generated join token; it is a development
// credential, not a production secret rotation scheme.
joinTokenTTL = 10 * 365 * 24 * time.Hour
@@ -226,6 +229,21 @@ func (s *Server) Start(ctx context.Context) error {
mux := http.NewServeMux()
cp.RegisterRoutes(mux)
+ // The console proxies /console/api/* to the loopback control plane and
+ // serves the embedded frontend; it queries /info at construction, which is
+ // already live on the loopback listener.
+ consoleSrv, err := console.NewServer(console.Config{
+ ControlPlaneURL: "http://" + cp.Addr(),
+ AdminToken: s.adminToken,
+ StaticFS: console.EmbeddedAssets(),
+ BasePath: consoleBasePath,
+ ExternalURL: s.opts.ExternalURL,
+ })
+ if err != nil {
+ return fmt.Errorf("failed to create console: %w", err)
+ }
+ mux.Handle(consoleBasePath+"/", consoleSrv.Handler())
+
wsAddr, err := wsListenMultiaddr(s.opts.BindAddress)
if err != nil {
return err
diff --git a/site/content/docs/development/testing.md b/site/content/docs/development/testing.md
index 9331f4e1..ad59f968 100644
--- a/site/content/docs/development/testing.md
+++ b/site/content/docs/development/testing.md
@@ -96,7 +96,7 @@ leaves the console running with its URL and admin token printed. Only the OIDC
issuer is a stand-in: it serves a discovery document but cannot sign tokens,
which is why enrollment uses bootstrap tokens rather than a JWT.
-The console serves its static assets from `cmd/sam-console/public`, so edits to
+The console serves its static assets from `internal/console/public`, so edits to
the HTML, CSS or JS need only a browser refresh; only Go changes need a rebuild.
## Troubleshooting
diff --git a/tests/integration/standalone_test.go b/tests/integration/standalone_test.go
index 16faba40..a4d2d7ee 100644
--- a/tests/integration/standalone_test.go
+++ b/tests/integration/standalone_test.go
@@ -16,10 +16,13 @@ package integration_test
import (
"context"
+ "io"
"net"
+ "net/http"
"os"
"path/filepath"
"strconv"
+ "strings"
"testing"
"time"
@@ -116,4 +119,22 @@ func TestStandaloneNodeJoin(t *testing.T) {
if got := samNode.Host.Network().Connectedness(routerID); got != network.Connected {
t.Fatalf("node connectedness to embedded router = %s, want Connected", got)
}
+
+ // The embedded web console is served through the same public port.
+ client := &http.Client{Timeout: 5 * time.Second}
+ resp, err := client.Get("http://" + srv.Addr() + "/console/")
+ if err != nil {
+ t.Fatalf("GET /console/ over the single port failed: %v", err)
+ }
+ body, err := io.ReadAll(resp.Body)
+ _ = resp.Body.Close()
+ if err != nil {
+ t.Fatalf("failed to read console body: %v", err)
+ }
+ if resp.StatusCode != http.StatusOK {
+ t.Fatalf("GET /console/ status = %s, want 200", resp.Status)
+ }
+ if !strings.Contains(string(body), "<html") {
+ t.Errorf("GET /console/ did not return the embedded frontend")
+ }
}
diff --git a/tests/ui/dev.sh b/tests/ui/dev.sh
index 9633c339..7d4f57d2 100755
--- a/tests/ui/dev.sh
+++ b/tests/ui/dev.sh
@@ -108,7 +108,7 @@ cat <<EOF
Control plane ${STACK_CP_URL}
Logs ${WORK_DIR}
- Static assets are served from cmd/sam-console/public, so edits to the HTML,
+ Static assets are served from internal/console/public, so edits to the HTML,
CSS or JS just need a browser refresh. Ctrl-C tears everything down.
EOF
diff --git a/tests/ui/lib/stack.sh b/tests/ui/lib/stack.sh
index 08266143..8840e4d2 100644
--- a/tests/ui/lib/stack.sh
+++ b/tests/ui/lib/stack.sh
@@ -105,7 +105,7 @@ stack_start_console() {
"${REPO_ROOT}/bin/sam-console" \
--control-plane "${STACK_CP_URL}" \
--bind-addr "${STACK_CONSOLE_ADDR}" \
- --static-dir "${REPO_ROOT}/cmd/sam-console/public" \
+ --static-dir "${REPO_ROOT}/internal/console/public" \
>"${WORK_DIR}/console.log" 2>&1 &
PIDS+=($!)
wait_for "${STACK_CONSOLE_URL}/" "console"