Skip to content

The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu

Address review findings on connect

shukieshah0d7f57edc48b
diff --git a/cli/beacon/internal/endpoint/asymptote/asymptote.go b/cli/beacon/internal/endpoint/asymptote/asymptote.go
index 6092ed9b..363ee635 100644
--- a/cli/beacon/internal/endpoint/asymptote/asymptote.go
+++ b/cli/beacon/internal/endpoint/asymptote/asymptote.go
@@ -103,10 +103,10 @@ type RenderOptions struct {
// RenderVectorConfig returns vector.toml with every environment reference replaced
// by a literal value, for a forwarder unit that must not depend on its
-// environment. It refuses non-https ingest URLs so a downgraded endpoint can never
-// receive a device key.
+// environment. It applies IsSecureURL, so a downgraded endpoint can never receive
+// a device key while a loopback development server still works.
func RenderVectorConfig(opts RenderOptions) (string, error) {
- if !strings.HasPrefix(strings.ToLower(opts.IngestURL), "https://") {
+ if !IsSecureURL(opts.IngestURL) {
return "", ErrInsecureIngestURL
}
if opts.SecretsFile == "" || opts.DataDir == "" {
@@ -153,6 +153,6 @@ type renderError string
func (e renderError) Error() string { return string(e) }
const (
- ErrInsecureIngestURL renderError = "asymptote ingest URL must use https://"
+ ErrInsecureIngestURL renderError = "asymptote ingest URL must use https:// (plain http is allowed only for a loopback development server)"
ErrIncompleteRender renderError = "asymptote forwarder render needs ingest URL, secrets file and data dir"
)
diff --git a/cli/beacon/internal/endpoint/asymptote/asymptote_test.go b/cli/beacon/internal/endpoint/asymptote/asymptote_test.go
index 7da534cd..286a940f 100644
--- a/cli/beacon/internal/endpoint/asymptote/asymptote_test.go
+++ b/cli/beacon/internal/endpoint/asymptote/asymptote_test.go
@@ -192,6 +192,9 @@ func TestRenderVectorConfigRefusesInsecureOrIncompleteInput(t *testing.T) {
if _, err := RenderVectorConfig(RenderOptions{LogPath: "/tmp/r.jsonl", IngestURL: "http://ingest.example.test", SecretsFile: "/s", DataDir: "/d"}); !errors.Is(err, ErrInsecureIngestURL) {
t.Fatalf("expected ErrInsecureIngestURL, got %v", err)
}
+ if _, err := RenderVectorConfig(RenderOptions{LogPath: "/tmp/r.jsonl", IngestURL: "http://127.0.0.1:8080", SecretsFile: "/s", DataDir: "/d"}); err != nil {
+ t.Fatalf("loopback http must be allowed for local development, got %v", err)
+ }
if _, err := RenderVectorConfig(RenderOptions{LogPath: "/tmp/r.jsonl", IngestURL: "https://ingest.example.test"}); !errors.Is(err, ErrIncompleteRender) {
t.Fatalf("expected ErrIncompleteRender, got %v", err)
}
diff --git a/cli/beacon/internal/endpoint/asymptote/connect.go b/cli/beacon/internal/endpoint/asymptote/connect.go
index bc756f0e..c445a072 100644
--- a/cli/beacon/internal/endpoint/asymptote/connect.go
+++ b/cli/beacon/internal/endpoint/asymptote/connect.go
@@ -9,6 +9,7 @@ import (
"path/filepath"
"time"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/auth"
endpointconfig "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/config"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/service"
)
@@ -47,13 +48,13 @@ type ConnectOptions struct {
// ConnectResult reports what Connect wrote and where telemetry now goes.
type ConnectResult struct {
- Enrollment Enrollment `json:"enrollment"`
- VectorConfig string `json:"vector_config"`
- SecretsFile string `json:"secrets_file"`
- UnitPath string `json:"unit_path"`
- Forwarder string `json:"forwarder"`
- ReEnrolled bool `json:"re_enrolled"`
- ForwarderState service.Status
+ Enrollment Enrollment `json:"enrollment"`
+ VectorConfig string `json:"vector_config"`
+ SecretsFile string `json:"secrets_file"`
+ UnitPath string `json:"unit_path"`
+ Forwarder string `json:"forwarder"`
+ ReEnrolled bool `json:"re_enrolled"`
+ ForwarderState service.Status `json:"forwarder_state"`
}
// Connect enrolls this machine and starts the forwarder.
@@ -94,12 +95,20 @@ func Connect(ctx context.Context, opts ConnectOptions) (*ConnectResult, error) {
if installID == "" && previous != nil {
installID = previous.InstallID
}
+ if installID == "" {
+ installID = ReadInstallID(opts.UserMode)
+ }
if installID == "" {
installID, err = newInstallID()
if err != nil {
return nil, err
}
}
+ // Pin the id before the dashboard learns it, so a failure after approval retries as
+ // the same device.
+ if err := WriteInstallID(opts.UserMode, installID); err != nil {
+ return nil, err
+ }
enrollOpts := opts.Enroll
enrollOpts.Device.InstallID = installID
if enrollOpts.Device.InstallMode == "" {
@@ -155,7 +164,7 @@ func Connect(ctx context.Context, opts ConnectOptions) (*ConnectResult, error) {
enrollment := Enrollment{
InstallID: installID,
IngestURL: result.IngestURL,
- DashboardURL: enrollDashboardURL(enrollOpts.DashboardURL),
+ DashboardURL: auth.ResolveDashboardURL(enrollOpts.DashboardURL),
DeviceID: result.DeviceID,
KeyPrefix: result.KeyPrefix,
OrganizationID: result.OrganizationID,
@@ -263,17 +272,6 @@ func displayOrg(r *EnrollResult) string {
return r.OrganizationID
}
-func enrollDashboardURL(flag string) string {
- // Mirrors auth.ResolveDashboardURL without importing it here again.
- if flag != "" {
- return flag
- }
- if env := os.Getenv("BEACON_DASHBOARD_URL"); env != "" {
- return env
- }
- return "https://asymptotelabs.ai"
-}
-
// newInstallID mints a random 128-bit identifier for this machine.
func newInstallID() (string, error) {
var buf [16]byte
diff --git a/cli/beacon/internal/endpoint/asymptote/connect_test.go b/cli/beacon/internal/endpoint/asymptote/connect_test.go
index e6141dd6..a5f348ce 100644
--- a/cli/beacon/internal/endpoint/asymptote/connect_test.go
+++ b/cli/beacon/internal/endpoint/asymptote/connect_test.go
@@ -305,6 +305,14 @@ func TestStatusReportsCredentialState(t *testing.T) {
if err := WriteSecrets(true, "bcn_device_abcdefgh_"+strings.Repeat("k", 43)); err != nil {
t.Fatal(err)
}
+ // Credentials alone (what disconnect --keep-credentials leaves) are not a connection.
+ kept := Status(true, StatusOptions{SkipCredentialCheck: true})
+ if kept.Enabled || kept.DeviceID != "dev-1" || !strings.Contains(kept.Message, "credentials for device dev-1 kept") {
+ t.Fatalf("credentials-only status = %+v", kept)
+ }
+ if err := os.WriteFile(VectorConfigPath(true), []byte("# rendered"), 0o644); err != nil {
+ t.Fatal(err)
+ }
for status, want := range map[int]string{http.StatusOK: "valid", http.StatusNoContent: "valid", http.StatusUnauthorized: "revoked", http.StatusForbidden: "revoked", http.StatusBadGateway: "unknown"} {
answer = status
got := Status(true, StatusOptions{HTTPClient: ingest.Client()})
@@ -337,3 +345,91 @@ func mustJSON(t *testing.T, v any) []byte {
}
return data
}
+
+func TestConnectPinsInstallIDBeforeEnrollmentSoRetriesReuseIt(t *testing.T) {
+ home := t.TempDir()
+ t.Setenv("HOME", home)
+ isolateVectorDiscovery(t)
+ fd := newFakeDashboard(t)
+ fwd := &fakeForwarder{supported: true}
+
+ // First attempt fails after approval (vector validate rejects the config).
+ if _, err := Connect(context.Background(), connectOptions(t, fd, fwd, fakeVector(t, "0.56.0", 1))); err == nil {
+ t.Fatal("expected validate failure")
+ }
+ fd.mu.Lock()
+ firstID := fd.init["device"].(map[string]any)["install_id"].(string)
+ fd.mu.Unlock()
+ if pinned := ReadInstallID(true); pinned == "" || pinned != firstID {
+ t.Fatalf("install id must be pinned before enrollment: file=%q sent=%q", pinned, firstID)
+ }
+ if _, err := LoadEnrollment(true); !errors.Is(err, ErrNotEnrolled) {
+ t.Fatal("no enrollment record may exist after a failed connect")
+ }
+
+ // The retry sends the same id, so the server rotates the device instead of adding one.
+ if _, err := Connect(context.Background(), connectOptions(t, fd, fwd, fakeVector(t, "0.56.0", 0))); err != nil {
+ t.Fatal(err)
+ }
+ fd.mu.Lock()
+ defer fd.mu.Unlock()
+ if got := fd.init["device"].(map[string]any)["install_id"]; got != firstID {
+ t.Fatalf("retry sent install_id %v, want %q", got, firstID)
+ }
+}
+
+func TestConnectResultJSONUsesSnakeCaseAndNormalizedDashboardURL(t *testing.T) {
+ home := t.TempDir()
+ t.Setenv("HOME", home)
+ isolateVectorDiscovery(t)
+ fd := newFakeDashboard(t)
+ opts := connectOptions(t, fd, &fakeForwarder{supported: true}, fakeVector(t, "0.56.0", 0))
+ opts.Enroll.DashboardURL = fd.server.URL + "/"
+ result, err := Connect(context.Background(), opts)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if result.Enrollment.DashboardURL != fd.server.URL {
+ t.Fatalf("dashboard URL must be normalized without a trailing slash: %q", result.Enrollment.DashboardURL)
+ }
+ var encoded map[string]any
+ if err := json.Unmarshal(mustJSON(t, result), &encoded); err != nil {
+ t.Fatal(err)
+ }
+ if _, ok := encoded["forwarder_state"]; !ok {
+ t.Fatalf("connect --json must expose forwarder_state: %v", encoded)
+ }
+ if _, ok := encoded["ForwarderState"]; ok {
+ t.Fatal("PascalCase field leaked into JSON")
+ }
+}
+
+func TestLoopbackIngestURLIsAcceptedEndToEnd(t *testing.T) {
+ home := t.TempDir()
+ t.Setenv("HOME", home)
+ isolateVectorDiscovery(t)
+ fd := newFakeDashboard(t)
+ fd.ingestURL = "http://127.0.0.1:9999"
+ result, err := Connect(context.Background(), connectOptions(t, fd, &fakeForwarder{supported: true}, fakeVector(t, "0.56.0", 0)))
+ if err != nil {
+ t.Fatalf("a loopback development ingest URL must work end to end: %v", err)
+ }
+ if result.Enrollment.IngestURL != "http://127.0.0.1:9999" {
+ t.Fatalf("ingest url = %q", result.Enrollment.IngestURL)
+ }
+ for _, c := range []struct {
+ url string
+ want bool
+ }{
+ {"https://ingest.example.test", true},
+ {"http://127.0.0.1:8080", true},
+ {"http://localhost", true},
+ {"http://ingest.example.test", false},
+ {"ftp://127.0.0.1", false},
+ {"", false},
+ } {
+ if got := IsSecureURL(c.url); got != c.want {
+ t.Errorf("IsSecureURL(%q) = %t, want %t", c.url, got, c.want)
+ }
+ }
+}
diff --git a/cli/beacon/internal/endpoint/asymptote/enroll.go b/cli/beacon/internal/endpoint/asymptote/enroll.go
index 8c8f1c57..f7f568d3 100644
--- a/cli/beacon/internal/endpoint/asymptote/enroll.go
+++ b/cli/beacon/internal/endpoint/asymptote/enroll.go
@@ -82,7 +82,7 @@ type enrollExchangeRequest struct {
// one-time code is exchanged together with the PKCE verifier that never left this process.
func Enroll(ctx context.Context, opts EnrollOptions) (*EnrollResult, error) {
dashboardURL := auth.ResolveDashboardURL(opts.DashboardURL)
- if !strings.HasPrefix(strings.ToLower(dashboardURL), "https://") && !isLoopback(dashboardURL) {
+ if !IsSecureURL(dashboardURL) {
return nil, fmt.Errorf("dashboard URL must use https://: %s", dashboardURL)
}
if opts.Device.InstallID == "" {
@@ -175,7 +175,7 @@ func validateEnrollResult(r *EnrollResult) error {
return errors.New("exchange response did not include a device key")
case r.DeviceID == "" || r.OrganizationID == "":
return errors.New("exchange response is missing the device or organization id")
- case !strings.HasPrefix(strings.ToLower(r.IngestURL), "https://") && !isLoopback(r.IngestURL):
+ case !IsSecureURL(r.IngestURL):
return fmt.Errorf("exchange response ingest URL must use https://: %q", r.IngestURL)
}
r.IngestURL = strings.TrimRight(r.IngestURL, "/")
@@ -194,12 +194,22 @@ func buildEnrollURL(dashboardURL, state string, port int) string {
return u.String()
}
-// isLoopback allows plain http only for local development servers.
-func isLoopback(raw string) bool {
- u, err := url.Parse(raw)
- if err != nil {
+// IsSecureURL is the one rule for where a device key may be sent: https anywhere, or
+// plain http only to a loopback address for local development. Enrollment, the exchange
+// response and the rendered forwarder config all apply it, so a URL that passes enrollment
+// can never be refused when the config is written.
+func IsSecureURL(raw string) bool {
+ u, err := url.Parse(strings.TrimSpace(raw))
+ if err != nil || u.Host == "" {
+ return false
+ }
+ switch strings.ToLower(u.Scheme) {
+ case "https":
+ return true
+ case "http":
+ host := u.Hostname()
+ return host == "127.0.0.1" || host == "localhost" || host == "::1"
+ default:
return false
}
- host := u.Hostname()
- return host == "127.0.0.1" || host == "localhost" || host == "::1"
}
diff --git a/cli/beacon/internal/endpoint/asymptote/enrollment.go b/cli/beacon/internal/endpoint/asymptote/enrollment.go
index 8bb8b160..2e4d386d 100644
--- a/cli/beacon/internal/endpoint/asymptote/enrollment.go
+++ b/cli/beacon/internal/endpoint/asymptote/enrollment.go
@@ -17,9 +17,13 @@ import (
const (
DirName = "asymptote"
EnrollmentFileName = "enrollment.json"
- SecretsFileName = "vector-secrets.json"
- VectorConfigName = "vector.toml"
- DataDirName = "vector-data"
+ // InstallIDFileName pins this machine's install id before enrollment starts, so a
+ // connect that fails after approval (validate, unit, load) retries with the same id and
+ // the server rotates the device's key instead of registering a second device.
+ InstallIDFileName = "install-id"
+ SecretsFileName = "vector-secrets.json"
+ VectorConfigName = "vector.toml"
+ DataDirName = "vector-data"
)
// Dir is the managed-ingest state directory for the selected endpoint mode.
@@ -30,6 +34,31 @@ func EnrollmentPath(userMode bool) string { return filepath.Join(Dir(userMode)
func SecretsPath(userMode bool) string { return filepath.Join(Dir(userMode), SecretsFileName) }
func VectorConfigPath(userMode bool) string { return filepath.Join(Dir(userMode), VectorConfigName) }
func DataDir(userMode bool) string { return filepath.Join(Dir(userMode), DataDirName) }
+func InstallIDPath(userMode bool) string { return filepath.Join(Dir(userMode), InstallIDFileName) }
+
+// ReadInstallID returns the pinned install id, or "" when none has been written.
+func ReadInstallID(userMode bool) string {
+ data, err := os.ReadFile(InstallIDPath(userMode))
+ if err != nil {
+ return ""
+ }
+ return strings.TrimSpace(string(data))
+}
+
+// WriteInstallID pins the install id for this machine.
+func WriteInstallID(userMode bool, installID string) error {
+ if err := ensureDir(userMode); err != nil {
+ return err
+ }
+ return writeFileAtomic(InstallIDPath(userMode), []byte(installID+"\n"), 0o600)
+}
+
+// Connected reports whether a forwarder is installed for this endpoint: an enrollment
+// record alone is not a connection, because disconnect --keep-credentials leaves it behind.
+func Connected(userMode bool) bool {
+ _, err := os.Stat(VectorConfigPath(userMode))
+ return err == nil
+}
// Enrollment is the non-secret record of a device's enrollment. Everything `beacon endpoint
// status` prints comes from here; the device key itself is only in the secrets file.
diff --git a/cli/beacon/internal/endpoint/asymptote/status.go b/cli/beacon/internal/endpoint/asymptote/status.go
index d0beae53..3ee49345 100644
--- a/cli/beacon/internal/endpoint/asymptote/status.go
+++ b/cli/beacon/internal/endpoint/asymptote/status.go
@@ -55,6 +55,17 @@ func Status(userMode bool, opts StatusOptions) ManagedIngestStatus {
}
return status
}
+ if !Connected(userMode) {
+ // disconnect --keep-credentials leaves the record and key for a later connect.
+ return ManagedIngestStatus{
+ Enabled: false,
+ DeviceID: enrollment.DeviceID,
+ KeyPrefix: enrollment.KeyPrefix,
+ OrganizationID: enrollment.OrganizationID,
+ OrganizationName: enrollment.OrganizationName,
+ Message: fmt.Sprintf("disconnected; credentials for device %s kept, run `beacon endpoint connect` to reuse them", enrollment.DeviceID),
+ }
+ }
status := ManagedIngestStatus{
Enabled: true,
IngestURL: enrollment.IngestURL,