The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu
Go agent-ai-cliagent-harnessesagent-securitybrowser-extensionciclaude-codecloudcodexcursordetection-engineeringjevknowledge-basememorymobile-device-managementobservabilitysecuritysecurity-information-and-event-managementsecurity-toolstelemetrytraces
fix(dashboard): Print the dashboard launch URL only after the port binds. (#1253)
Deep Shah3ef124241f06
diff --git a/cli/beacon/cmd/endpoint_dashboard_access_test.go b/cli/beacon/cmd/endpoint_dashboard_access_test.goindex 525b0352..ccbf64bb 100644--- a/cli/beacon/cmd/endpoint_dashboard_access_test.go+++ b/cli/beacon/cmd/endpoint_dashboard_access_test.go@@ -2,6 +2,7 @@ package cmdimport ("errors"+ "net""path/filepath""strings""testing"@@ -17,10 +18,12 @@ func useDashboardTestDefaults(t *testing.T) *dashboard.Options {oldOpts := endpointOptsoldListen := dashboardListenAndServeoldSwitch := dashboardSystemDisabled+ oldOpen := openDashboardBrowsert.Cleanup(func() {endpointOpts = oldOptsdashboardListenAndServe = oldListendashboardSystemDisabled = oldSwitch+ openDashboardBrowser = oldOpen})home := t.TempDir()testenv.SetHome(t, home)@@ -28,7 +31,10 @@ func useDashboardTestDefaults(t *testing.T) *dashboard.Options {t.Fatal(err)}served := &dashboard.Options{}- dashboardListenAndServe = func(opts dashboard.Options) error { *served = opts; return nil }+ dashboardListenAndServe = func(opts dashboard.Options) error {+ *served = opts+ return acceptDashboardBind(opts)+ }endpointOpts.userMode = trueendpointOpts.systemMode = falseendpointOpts.logPath = ""@@ -63,6 +69,47 @@ func TestRunEndpointDashboardPrintsTheLaunchURL(t *testing.T) {}}+func TestRunEndpointDashboardOpensTheBrowserOnlyAfterThePortBinds(t *testing.T) {+ served := useDashboardTestDefaults(t)+ var opened string+ openDashboardBrowser = func(url string) error { opened = url; return nil }+ endpointOpts.dashboardOpen = true+ out, err := captureStdout(t, func() error { return runEndpointDashboard(nil, nil) })+ if err != nil {+ t.Fatal(err)+ }+ want := "http://127.0.0.1:8765/?token=" + served.Token+ if opened != want {+ t.Fatalf("opened %q, want %q", opened, want)+ }+ if strings.Count(out, served.Token) != 1 {+ t.Fatalf("output = %q", out)+ }++ opened = ""+ dashboardListenAndServe = func(dashboard.Options) error {+ return errors.New("listen tcp 127.0.0.1:8765: bind: address already in use")+ }+ out, err = captureStdout(t, func() error { return runEndpointDashboard(nil, nil) })+ if err == nil || !strings.Contains(err.Error(), "bind") {+ t.Fatalf("taken port = %v", err)+ }+ if opened != "" || strings.Contains(out, "token=") || strings.Contains(out, "Beacon endpoint dashboard:") {+ t.Fatalf("a failed bind disclosed the launch: opened %q, output %q", opened, out)+ }+}++func acceptDashboardBind(opts dashboard.Options) error {+ if opts.Ready == nil {+ return nil+ }+ addr, err := net.ResolveTCPAddr("tcp", opts.Addr)+ if err != nil {+ return err+ }+ return opts.Ready(addr)+}+func TestRunEndpointDashboardRefusesWhenTheAdministratorDisabledIt(t *testing.T) {served := useDashboardTestDefaults(t)dashboardSystemDisabled = func() (bool, error) { return true, nil }diff --git a/cli/beacon/cmd/endpoint_install.go b/cli/beacon/cmd/endpoint_install.goindex d95b85c2..a6cb07a3 100644--- a/cli/beacon/cmd/endpoint_install.go+++ b/cli/beacon/cmd/endpoint_install.go@@ -6,6 +6,7 @@ import ("errors""fmt""io"+ "net""os""strings"@@ -67,6 +68,9 @@ var endpointDashboardCmd = &cobra.Command{var dashboardListenAndServe = dashboard.ListenAndServe+// openDashboardBrowser is dashboard.OpenBrowser. Tests replace it to see whether a launch opened one.+var openDashboardBrowser = dashboard.OpenBrowser+func runEndpointDashboard(cmd *cobra.Command, args []string) error {cfg := loadOrDefaultConfig()userMode := endpointUserMode()@@ -82,33 +86,37 @@ func runEndpointDashboard(cmd *cobra.Command, args []string) error {if err := refuseDisabledDashboard(); err != nil {return err}- // The launch secret lives only in memory and in the URL printed here, which is the one way in:- // another account that reaches the loopback port without it is refused.+ // The launch secret lives only in memory and in the URL printed after the port binds, which is+ // the one way in: another account that reaches the loopback port without it is refused.token, err := dashboard.NewToken()if err != nil {return fmt.Errorf("create the dashboard launch secret: %w", err)}- url := dashboard.LaunchURL(endpointOpts.dashboardAddr, token, "/")- fmt.Printf("Beacon endpoint dashboard: %s\n", url)- fmt.Printf("Runtime log: %s\n", cfg.LogPath)- if runtimeLog.Warning != "" {- fmt.Printf("Runtime log source: %s\n", runtimeLog.Warning)- }- if endpointOpts.dashboardOpen {- if err := dashboard.OpenBrowser(url); err != nil {- // Over SSH the dashboard is still worth serving: forward its port and open it on- // the client.- if !errors.Is(err, auth.ErrNoDisplay) {- return err- }- fmt.Printf("Not opening a browser (%v).\n", err)- }- }return dashboardListenAndServe(dashboard.Options{Addr: endpointOpts.dashboardAddr,LogPath: endpointOpts.logPath,UserMode: userMode,Token: token,+ Ready: func(addr net.Addr) error {+ url := dashboard.LaunchURL(addr.String(), token, "/")+ fmt.Printf("Beacon endpoint dashboard: %s\n", url)+ fmt.Printf("Runtime log: %s\n", cfg.LogPath)+ if runtimeLog.Warning != "" {+ fmt.Printf("Runtime log source: %s\n", runtimeLog.Warning)+ }+ if !endpointOpts.dashboardOpen {+ return nil+ }+ if err := openDashboardBrowser(url); err != nil {+ // Over SSH the dashboard is still worth serving: forward its port and open it on+ // the client.+ if !errors.Is(err, auth.ErrNoDisplay) {+ return err+ }+ fmt.Printf("Not opening a browser (%v).\n", err)+ }+ return nil+ },})}diff --git a/cli/beacon/cmd/lenses_tools.go b/cli/beacon/cmd/lenses_tools.goindex 231db23c..653717ac 100644--- a/cli/beacon/cmd/lenses_tools.go+++ b/cli/beacon/cmd/lenses_tools.go@@ -3,6 +3,7 @@ package cmdimport ("errors""fmt"+ "net""net/url""os""path/filepath"@@ -200,19 +201,9 @@ installed; use 'beacon lenses add' when it is done. Runs until interrupted.`,if session == "" {session, _ = latestSession(logPath)}- page := dashboard.LaunchURL(lensToolsOpts.addr, token, "/")+ pagePath := "/"if session != "" {- page = dashboard.LaunchURL(lensToolsOpts.addr, token, "/session.html?"+url.Values{"id": {session}, "lens": {manifest.ID}}.Encode())- }- fmt.Fprintf(out, "Previewing %s (%s) from %s\n", manifest.Title, manifest.ID, file)- if session == "" {- fmt.Fprintln(out, "No sessions in the runtime log yet; open a session in the dashboard and add the lens from its + menu.")- }- fmt.Fprintf(out, "Open: %s\nEdits to the file show on reload. Press Ctrl-C to stop.\n", page)- if lensToolsOpts.open {- if err := dashboard.OpenBrowser(page); err != nil && !errors.Is(err, auth.ErrNoDisplay) {- return err- }+ pagePath = "/session.html?" + url.Values{"id": {session}, "lens": {manifest.ID}}.Encode()}return dashboardListenAndServe(dashboard.Options{Addr: lensToolsOpts.addr,@@ -220,6 +211,21 @@ installed; use 'beacon lenses add' when it is done. Runs until interrupted.`,UserMode: lensesUserMode(),LensFiles: []string{file},Token: token,+ Ready: func(addr net.Addr) error {+ page := dashboard.LaunchURL(addr.String(), token, pagePath)+ fmt.Fprintf(out, "Previewing %s (%s) from %s\n", manifest.Title, manifest.ID, file)+ if session == "" {+ fmt.Fprintln(out, "No sessions in the runtime log yet; open a session in the dashboard and add the lens from its + menu.")+ }+ fmt.Fprintf(out, "Open: %s\nEdits to the file show on reload. Press Ctrl-C to stop.\n", page)+ if !lensToolsOpts.open {+ return nil+ }+ if err := openDashboardBrowser(page); err != nil && !errors.Is(err, auth.ErrNoDisplay) {+ return err+ }+ return nil+ },})},}diff --git a/cli/beacon/cmd/lenses_tools_test.go b/cli/beacon/cmd/lenses_tools_test.goindex ee32a187..b99c873e 100644--- a/cli/beacon/cmd/lenses_tools_test.go+++ b/cli/beacon/cmd/lenses_tools_test.go@@ -3,6 +3,7 @@ package cmdimport ("bytes""encoding/json"+ "errors""os""path/filepath""strings"@@ -163,9 +164,12 @@ func TestLensesPreviewServesTheFileAgainstARealSession(t *testing.T) {useLensToolsDefaults(t)lensToolsOpts.logPath = writeLensLog(t)var served dashboard.Options- prev := dashboardListenAndServe- dashboardListenAndServe = func(opts dashboard.Options) error { served = opts; return nil }- t.Cleanup(func() { dashboardListenAndServe = prev })+ prev, prevOpen := dashboardListenAndServe, openDashboardBrowser+ dashboardListenAndServe = func(opts dashboard.Options) error {+ served = opts+ return acceptDashboardBind(opts)+ }+ t.Cleanup(func() { dashboardListenAndServe, openDashboardBrowser = prev, prevOpen })file := writeTestLens(t, t.TempDir(), "my-lens", "1")cmd, buf := newCmd()@@ -198,3 +202,25 @@ func TestLensesPreviewServesTheFileAgainstARealSession(t *testing.T) {t.Fatal("a non-loopback preview address was accepted")}}++func TestLensesPreviewDoesNotDiscloseTheTokenWhenThePortIsTaken(t *testing.T) {+ useLensToolsDefaults(t)+ lensToolsOpts.logPath = writeLensLog(t)+ lensToolsOpts.open = true+ opened := false+ prev, prevOpen := dashboardListenAndServe, openDashboardBrowser+ dashboardListenAndServe = func(dashboard.Options) error {+ return errors.New("listen tcp 127.0.0.1:8766: bind: address already in use")+ }+ openDashboardBrowser = func(string) error { opened = true; return nil }+ t.Cleanup(func() { dashboardListenAndServe, openDashboardBrowser = prev, prevOpen })++ cmd, buf := newCmd()+ err := lensesPreviewCmd.RunE(cmd, []string{writeTestLens(t, t.TempDir(), "my-lens", "1")})+ if err == nil || !strings.Contains(err.Error(), "bind") {+ t.Fatalf("taken port = %v", err)+ }+ if opened || strings.Contains(buf.String(), "token=") || strings.Contains(buf.String(), "Open:") {+ t.Fatalf("a failed bind disclosed the preview: opened %v, output %q", opened, buf.String())+ }+}diff --git a/cli/beacon/internal/endpoint/dashboard/access_test.go b/cli/beacon/internal/endpoint/dashboard/access_test.goindex d2677445..bc9ce79c 100644--- a/cli/beacon/internal/endpoint/dashboard/access_test.go+++ b/cli/beacon/internal/endpoint/dashboard/access_test.go@@ -3,12 +3,14 @@ package dashboardimport ("errors""io"+ "net""net/http""net/http/cookiejar""net/http/httptest""net/url""strings""testing"+ "time")const accessTestAddr = "127.0.0.1:8765"@@ -65,6 +67,52 @@ func TestServedHandlerRequiresAToken(t *testing.T) {}}+func TestListenAndServeAnnouncesOnlyAfterThePortIsBound(t *testing.T) {+ token, err := NewToken()+ if err != nil {+ t.Fatal(err)+ }+ busy, err := net.Listen("tcp", "127.0.0.1:0")+ if err != nil {+ t.Fatal(err)+ }+ defer busy.Close()+ announced := false+ err = ListenAndServe(Options{+ Addr: busy.Addr().String(), UserMode: true, Token: token,+ Ready: func(net.Addr) error { announced = true; return nil },+ })+ if err == nil {+ t.Fatal("ListenAndServe bound a port that was already taken")+ }+ if announced {+ t.Fatal("Ready ran even though the listen failed")+ }++ errCh := make(chan error, 1)+ go func() {+ errCh <- ListenAndServe(Options{+ Addr: "127.0.0.1:0", UserMode: true, Token: token,+ Ready: func(addr net.Addr) error {+ conn, dialErr := net.Dial("tcp", addr.String())+ if dialErr != nil {+ return dialErr+ }+ conn.Close()+ return errors.New("stop after bind")+ },+ })+ }()+ select {+ case err := <-errCh:+ if err == nil || err.Error() != "stop after bind" {+ t.Fatalf("ListenAndServe = %v", err)+ }+ case <-time.After(5 * time.Second):+ t.Fatal("Ready was not called after the port bound")+ }+}+func TestDashboardRefusesRequestsWithoutTheLaunchSecret(t *testing.T) {srv, token := accessServer(t)client := noRedirectClient(nil)diff --git a/cli/beacon/internal/endpoint/dashboard/e2eserver/main.go b/cli/beacon/internal/endpoint/dashboard/e2eserver/main.goindex 966fe8bf..54110bff 100644--- a/cli/beacon/internal/endpoint/dashboard/e2eserver/main.go+++ b/cli/beacon/internal/endpoint/dashboard/e2eserver/main.go@@ -10,6 +10,7 @@ package mainimport ("flag""fmt"+ "net""os""strings"@@ -28,15 +29,24 @@ func main() {flag.Var(&lenses, "lens", "lens file to serve (repeatable)")flag.Parse()token := os.Getenv("BEACON_E2E_DASHBOARD_TOKEN")+ printURL := falseif token == "" {+ printURL = truevar err errorif token, err = dashboard.NewToken(); err != nil {fmt.Fprintln(os.Stderr, err)os.Exit(1)}- fmt.Println(dashboard.LaunchURL(*addr, token, "/"))}- err := dashboard.ListenAndServe(dashboard.Options{Addr: *addr, LogPath: *logPath, UserMode: true, LensFiles: lenses, Token: token})+ err := dashboard.ListenAndServe(dashboard.Options{+ Addr: *addr, LogPath: *logPath, UserMode: true, LensFiles: lenses, Token: token,+ Ready: func(bound net.Addr) error {+ if printURL {+ fmt.Println(dashboard.LaunchURL(bound.String(), token, "/"))+ }+ return nil+ },+ })if err != nil {fmt.Fprintln(os.Stderr, err)os.Exit(1)diff --git a/cli/beacon/internal/endpoint/dashboard/server.go b/cli/beacon/internal/endpoint/dashboard/server.goindex 7c8ae720..6964b036 100644--- a/cli/beacon/internal/endpoint/dashboard/server.go+++ b/cli/beacon/internal/endpoint/dashboard/server.go@@ -38,6 +38,10 @@ type Options struct {// Token is this launch's secret (NewToken). ListenAndServe refuses to start without one and// serves only requests that carry it (RequireToken); print it only inside LaunchURL.Token string+ // Ready runs after the port is bound and before requests are served. The dashboard command+ // and lens preview print the launch URL and open the browser from here, so a failed bind+ // never discloses the token. A non-nil error closes the listener and is returned.+ Ready func(addr net.Addr) error}type StatusResponse struct {@@ -417,12 +421,22 @@ func ListenAndServe(opts Options) error {if err != nil {return err}+ ln, err := net.Listen("tcp", opts.Addr)+ if err != nil {+ return err+ }+ if opts.Ready != nil {+ if err := opts.Ready(ln.Addr()); err != nil {+ ln.Close()+ return err+ }+ }server := &http.Server{Addr: opts.Addr,Handler: handler,ReadHeaderTimeout: 5 * time.Second,}- return server.ListenAndServe()+ return server.Serve(ln)}// servedHandler is the handler ListenAndServe serves: Handler behind the loopback Host check and