Skip to content

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

Add beacon endpoint connect and disconnect for Asymptote managed ingest

shukieshah6b231436e4ee
diff --git a/CLAUDE.md b/CLAUDE.md
index 8b16966f..24292a2e 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -40,6 +40,7 @@ Supported runtime surfaces today:
- Claude Cowork admin-configured OpenTelemetry setup guidance and local validation.
- Browser chat telemetry through an optional Chrome MV3 extension (`browser-extension/`) covering claude.ai and chatgpt.com. A main-world interceptor tees the streamed response, a per-site adapter parses it into a normalized turn, and the service worker POSTs OTLP GenAI logs to the local collector on `127.0.0.1:4318`; the extension never writes files and never contacts a remote endpoint. `harness.name` resolves to `claude_web` or `chatgpt_web` (already handled by `NormalizeHarnessName` in `pkg/asymptoteobserve/harness.go`, where the browser cases must stay above the generic `claude` rule) and `harness.collection_method` is `otlp`. Scope is deliberately narrow: only those origins' chat streams, never other tabs or general browsing. Retention defaults to `full`, so prompt and response text is retained by default; this is documented rather than defaulted down, because browser chat telemetry without content has no investigative value. Treat the adapters as experimental, since both sites' stream formats are private and undocumented.
- `beaconjson` OpenTelemetry Collector exporter that converts OTLP logs, traces, metrics, and resource attributes into Beacon endpoint JSONL.
+- Asymptote Managed forwarding, the one opt-in network channel for telemetry: `beacon endpoint connect` (`cli/beacon/cmd/endpoint_connect.go`, `cli/beacon/internal/endpoint/asymptote`) runs a browser PKCE approval against the dashboard's `/cli/enroll` page, stores the per-device key in `<BaseDir>/asymptote/vector-secrets.json` (0600, 0700 dir), renders the `asymptote` pack into `vector.toml`, validates it, and runs Vector as `com.beacon.endpoint.asymptote-forwarder` / `beacon-asymptote-forwarder.service` through `service.ForwarderManager` (user or system mode; refused in supervised mode). `enrollment.json` and `config.json`'s `managed_ingest` block carry only non-secret identity; `beacon endpoint status` reports forwarder state and a live credential check (`GET /v1/ingest/health`, 3 s timeout); `disconnect` and `uninstall` remove the forwarder and credentials but never revoke server-side.
- Asymptote Observe TypeScript SDK instrumentation for cloud applications, starting from OpenTelemetry/OpenLLMetry patterns and `observe()` wrappers.
- Elasticsearch/Filebeat content pack generation for forwarding local Beacon JSONL into customer-managed Elastic deployments or the bundled loopback-only development stack.
- A local-only dashboard served by `beacon endpoint dashboard`, bound to loopback by default and backed by the runtime JSONL log.
@@ -146,8 +147,19 @@ go run . endpoint fx status # sessions fx has written and how much Beacon
go run . endpoint fx sync --print # map records to events without writing anything
```
-Run the Asymptote Managed forwarder by hand during manual testing (needs a device key from
-enrollment and Vector on the machine; `/opt/beacon/bin/vector` from the signed package works):
+Connect an endpoint to Asymptote Managed during manual testing (needs Vector 0.56+ on the machine;
+`/opt/beacon/bin/vector` from the signed package works, and a browser signed in to an org that has
+managed ingest enabled):
+
+```bash
+cd cli/beacon
+go run . endpoint connect # browser approval → device key → forwarder service
+go run . endpoint status --json | jq .managed_ingest
+go run . endpoint disconnect # stop the forwarder and remove the local key
+```
+
+Run the Asymptote Managed forwarder by hand instead (a device key from `beacon-ingest/scripts/mint_test_device.py`
+or a previous connect):
```bash
cd cli/beacon
@@ -445,6 +457,7 @@ unpacked through Chrome's developer mode.
- Keep `gen_ai.usage` as the single canonical token-usage representation: normalize all runtime token telemetry (span attributes, metric datapoints, legacy `llm.usage.*` aliases) into it, mirror OTel GenAI semconv JSON names exactly, and never add parallel or per-harness token fields. `gen_ai.usage.cost_usd` carries runtime-reported cost only; do not derive cost from local pricing tables.
- When adding a new signal, include stable identifiers/counts/hashes alongside any retained raw content, and route raw fields through redaction, sanitization, truncation, and event-size controls.
- Keep the dashboard read-only. It should inspect local status and JSONL events but must not mutate endpoint configuration or telemetry.
+- The Asymptote device key has exactly one home, `<BaseDir>/asymptote/vector-secrets.json`, read by Vector's `secret` file backend. Never copy it into `config.json`, `vector.toml`, a service unit, an environment variable, a log line, or a `--json` result; `HasSecretDestinations` is unchanged because the key is not in `config.json`. `internal/auth` is flow-agnostic (PKCE, loopback callback server with an injected exchange function, browser opener, `PostJSON`); new browser flows reuse it rather than adding a second callback server. `connect` must fail before opening a browser when Vector or a service manager is missing, so no key is minted that cannot be used.
- Keep the release readiness guidance in `README.md` up to date when install, packaging, collector, or dashboard behavior changes.
## CI Expectations
diff --git a/cli/beacon/cmd/endpoint_connect.go b/cli/beacon/cmd/endpoint_connect.go
new file mode 100644
index 00000000..c126f82d
--- /dev/null
+++ b/cli/beacon/cmd/endpoint_connect.go
@@ -0,0 +1,236 @@
+package cmd
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "os"
+ "os/exec"
+ "runtime"
+ "strings"
+
+ "github.com/spf13/cobra"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/auth"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/asymptote"
+ endpointconfig "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/config"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/lifecycle"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/version"
+)
+
+var connectOpts struct {
+ dashboardURL string
+ noBrowser bool
+ vectorBin string
+ keepCredentials bool
+}
+
+var endpointConnectCmd = &cobra.Command{
+ Use: "connect",
+ Short: "Forward this endpoint's telemetry to Asymptote managed ingest",
+ Long: `Connect this endpoint to Asymptote managed ingest.
+
+Opens the Asymptote dashboard so a member of your organization can approve this
+device, then stores the per-device key it receives in a private secrets file
+and starts a Vector forwarder that ships the runtime and inventory JSONL to
+Asymptote. Nothing recorded before approval is sent. Re-running on a connected
+machine rotates its key in place.
+
+Requires Vector 0.56 or newer: the signed macOS package installs it at
+/opt/beacon/bin/vector, Homebrew provides it as "vector", and Linux packages are
+at https://vector.dev. Revoke a device from the dashboard's Beacon Endpoints
+page; run "beacon endpoint disconnect" to stop forwarding locally.`,
+ SilenceUsage: true,
+ RunE: runEndpointConnect,
+}
+
+var endpointDisconnectCmd = &cobra.Command{
+ Use: "disconnect",
+ Short: "Stop forwarding to Asymptote and remove the local forwarder",
+ Long: `Stop the Asymptote forwarder and remove its configuration and, unless
+--keep-credentials is given, the stored device key and enrollment record.
+
+This does not revoke the device on the server. Revoke it from the dashboard's
+Beacon Endpoints page so the key can never be used again.`,
+ SilenceUsage: true,
+ RunE: runEndpointDisconnect,
+}
+
+func init() {
+ for _, c := range []*cobra.Command{endpointConnectCmd, endpointDisconnectCmd} {
+ addEndpointPathFlags(c)
+ c.Flags().BoolVar(&endpointOpts.jsonOutput, "json", false, "Print output as JSON")
+ }
+ endpointConnectCmd.Flags().StringVar(&connectOpts.dashboardURL, "dashboard-url", "", "Asymptote dashboard URL (defaults to "+auth.DefaultDashboardURL+", or "+auth.DashboardURLEnv+")")
+ endpointConnectCmd.Flags().BoolVar(&connectOpts.noBrowser, "no-browser", false, "Print the approval URL instead of opening a browser")
+ endpointConnectCmd.Flags().StringVar(&connectOpts.vectorBin, "vector-bin", "", "Vector binary to run (defaults to "+asymptote.VectorBinEnv+", "+asymptote.PackagedVectorPath+", Homebrew, then PATH)")
+ endpointDisconnectCmd.Flags().BoolVar(&connectOpts.keepCredentials, "keep-credentials", false, "Keep the enrollment record and device key so a later connect can reuse this device")
+ endpointCmd.AddCommand(endpointConnectCmd)
+ endpointCmd.AddCommand(endpointDisconnectCmd)
+}
+
+func runEndpointConnect(cmd *cobra.Command, args []string) error {
+ userMode := endpointUserMode()
+ if !userMode && !lifecycle.HasSystemPrivileges() {
+ return fmt.Errorf("connecting a system endpoint needs root: rerun with sudo, or pass --user for a per-user install")
+ }
+ cfg := loadOrDefaultConfig()
+ hostname, _ := os.Hostname()
+ out := cmd.OutOrStdout()
+ if endpointOpts.jsonOutput {
+ out = cmd.ErrOrStderr()
+ }
+ result, err := asymptote.Connect(context.Background(), asymptote.ConnectOptions{
+ UserMode: userMode,
+ LogPath: cfg.LogPath,
+ VectorBin: connectOpts.vectorBin,
+ Out: out,
+ Enroll: asymptote.EnrollOptions{
+ DashboardURL: connectOpts.dashboardURL,
+ NoBrowser: connectOpts.noBrowser,
+ OpenBrowser: connectBrowserOpener(userMode),
+ Device: asymptote.DeviceInfo{
+ Hostname: hostname,
+ OS: runtime.GOOS,
+ Arch: runtime.GOARCH,
+ BeaconVersion: version.GetVersion(),
+ },
+ },
+ })
+ if err != nil {
+ return err
+ }
+ if endpointOpts.jsonOutput {
+ return json.NewEncoder(os.Stdout).Encode(result)
+ }
+ fmt.Fprintf(out, "Connected to Asymptote as device %s", result.Enrollment.DeviceID)
+ if result.Enrollment.OrganizationName != "" {
+ fmt.Fprintf(out, " for %s", result.Enrollment.OrganizationName)
+ }
+ fmt.Fprintln(out)
+ fmt.Fprintf(out, "Forwarder: %s (loaded=%t running=%t)\n", result.Forwarder, result.ForwarderState.Loaded, result.ForwarderState.Running)
+ fmt.Fprintf(out, "Vector config: %s\n", result.VectorConfig)
+ fmt.Fprintf(out, "Device key: %s (never printed; the Vector forwarder reads it)\n", result.SecretsFile)
+ fmt.Fprintf(out, "Events recorded from now on appear on %s/dashboard/telemetry. Revoke this device from %s/dashboard/endpoints.\n",
+ result.Enrollment.DashboardURL, result.Enrollment.DashboardURL)
+ return nil
+}
+
+func runEndpointDisconnect(cmd *cobra.Command, args []string) error {
+ userMode := endpointUserMode()
+ if !userMode && !lifecycle.HasSystemPrivileges() {
+ return fmt.Errorf("disconnecting a system endpoint needs root: rerun with sudo, or pass --user for a per-user install")
+ }
+ enrollment, loadErr := asymptote.LoadEnrollment(userMode)
+ cfg := loadOrDefaultConfig()
+ if err := asymptote.Disconnect(asymptote.DisconnectOptions{
+ UserMode: userMode,
+ LogPath: cfg.LogPath,
+ KeepCredentials: connectOpts.keepCredentials,
+ }); err != nil {
+ return err
+ }
+ if endpointOpts.jsonOutput {
+ return json.NewEncoder(os.Stdout).Encode(map[string]any{
+ "disconnected": true,
+ "kept_credentials": connectOpts.keepCredentials,
+ "device_id": deviceIDOrEmpty(enrollment, loadErr),
+ })
+ }
+ out := cmd.OutOrStdout()
+ fmt.Fprintln(out, "Asymptote forwarder stopped and removed.")
+ if connectOpts.keepCredentials {
+ fmt.Fprintf(out, "Enrollment record and device key kept under %s.\n", asymptote.Dir(userMode))
+ } else {
+ fmt.Fprintf(out, "Local enrollment record and device key removed from %s.\n", asymptote.Dir(userMode))
+ }
+ if loadErr == nil && enrollment != nil {
+ fmt.Fprintf(out, "The device %s is still registered server-side; revoke it from %s/dashboard/endpoints.\n", enrollment.DeviceID, enrollment.DashboardURL)
+ } else {
+ fmt.Fprintln(out, "Revoke the device from the dashboard's Beacon Endpoints page if it is still registered.")
+ }
+ return nil
+}
+
+func deviceIDOrEmpty(e *asymptote.Enrollment, err error) string {
+ if err != nil || e == nil {
+ return ""
+ }
+ return e.DeviceID
+}
+
+// connectBrowserOpener returns the browser opener for enrollment. A system-mode connect runs
+// as root, where opening a browser would start it as root (or fail under launchd); it opens
+// as the active console user instead, which is the person sitting at the machine.
+func connectBrowserOpener(userMode bool) func(string) error {
+ if userMode || os.Geteuid() != 0 {
+ return nil
+ }
+ info, ok, err := defaultActiveConsoleUser()
+ if err != nil || !ok {
+ return nil
+ }
+ return func(url string) error {
+ var opener []string
+ switch runtime.GOOS {
+ case "darwin":
+ opener = []string{"open", url}
+ case "linux":
+ opener = []string{"xdg-open", url}
+ default:
+ return auth.OpenBrowser(url)
+ }
+ args := append([]string{"-u", info.Username, "env", "HOME=" + info.HomeDir, "USER=" + info.Username, "LOGNAME=" + info.Username}, opener...)
+ cmd := exec.Command("sudo", args...)
+ cmd.Stdout, cmd.Stderr = nil, nil
+ return cmd.Start()
+ }
+}
+
+// managedIngestStatusLine renders the human status line for `beacon endpoint status`.
+func managedIngestStatusLine(status asymptote.ManagedIngestStatus) string {
+ if !status.Enabled {
+ if status.Message != "" {
+ return "Asymptote managed ingest: not connected (" + status.Message + ")"
+ }
+ return "Asymptote managed ingest: not connected (run `beacon endpoint connect`)"
+ }
+ var b strings.Builder
+ b.WriteString("Asymptote managed ingest: connected")
+ if status.OrganizationName != "" {
+ fmt.Fprintf(&b, " to %s", status.OrganizationName)
+ }
+ fmt.Fprintf(&b, " as device %s", status.DeviceID)
+ fmt.Fprintf(&b, "; forwarder loaded=%t running=%t", status.Forwarder.Loaded, status.Forwarder.Running)
+ switch status.Credential {
+ case "valid":
+ b.WriteString("; credential valid")
+ case "revoked":
+ b.WriteString("; credential revoked (run `beacon endpoint connect` to re-enroll)")
+ case "unknown":
+ b.WriteString("; credential unknown (" + status.CredentialMessage + ")")
+ }
+ if status.BufferBytes > 0 {
+ fmt.Fprintf(&b, "; buffer %s", humanBytes(status.BufferBytes))
+ }
+ return b.String()
+}
+
+func humanBytes(n int64) string {
+ const unit = 1024
+ if n < unit {
+ return fmt.Sprintf("%d B", n)
+ }
+ div, exp := int64(unit), 0
+ for m := n / unit; m >= unit; m /= unit {
+ div *= unit
+ exp++
+ }
+ return fmt.Sprintf("%.1f %ciB", float64(n)/float64(div), "KMGTPE"[exp])
+}
+
+// managedIngestFromConfig reports whether config.json says this endpoint is connected, for
+// callers that must not touch the network or the secrets file.
+func managedIngestFromConfig(cfg endpointconfig.Config) bool {
+ return cfg.ManagedIngest != nil && cfg.ManagedIngest.Enabled
+}
diff --git a/cli/beacon/cmd/endpoint_connect_test.go b/cli/beacon/cmd/endpoint_connect_test.go
new file mode 100644
index 00000000..41991788
--- /dev/null
+++ b/cli/beacon/cmd/endpoint_connect_test.go
@@ -0,0 +1,78 @@
+package cmd
+
+import (
+ "strings"
+ "testing"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/asymptote"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/service"
+)
+
+func TestEndpointConnectAndDisconnectCommandsRegistered(t *testing.T) {
+ for _, name := range []string{"connect", "disconnect"} {
+ cmd, _, err := endpointCmd.Find([]string{name})
+ if err != nil || cmd == nil || cmd.Use != name {
+ t.Fatalf("endpoint %s not registered: %v %#v", name, err, cmd)
+ }
+ for _, flag := range []string{"user", "system", "log-path", "json"} {
+ if cmd.Flags().Lookup(flag) == nil {
+ t.Fatalf("endpoint %s missing --%s", name, flag)
+ }
+ }
+ }
+ connect, _, _ := endpointCmd.Find([]string{"connect"})
+ for _, flag := range []string{"dashboard-url", "no-browser", "vector-bin"} {
+ if connect.Flags().Lookup(flag) == nil {
+ t.Fatalf("connect missing --%s", flag)
+ }
+ }
+ disconnect, _, _ := endpointCmd.Find([]string{"disconnect"})
+ if disconnect.Flags().Lookup("keep-credentials") == nil {
+ t.Fatal("disconnect missing --keep-credentials")
+ }
+ for _, removed := range []string{"login", "ingest"} {
+ if cmd, _, err := rootCmd.Find([]string{removed}); err == nil && cmd != nil && cmd.Use == removed {
+ t.Fatalf("removed command %q is still registered", removed)
+ }
+ }
+}
+
+func TestManagedIngestStatusLine(t *testing.T) {
+ notConnected := managedIngestStatusLine(asymptote.ManagedIngestStatus{})
+ if !strings.Contains(notConnected, "not connected") || !strings.Contains(notConnected, "beacon endpoint connect") {
+ t.Fatalf("not connected line = %q", notConnected)
+ }
+ connected := managedIngestStatusLine(asymptote.ManagedIngestStatus{
+ Enabled: true,
+ DeviceID: "dev-1",
+ OrganizationName: "Asymptote Test",
+ Forwarder: service.Status{Loaded: true, Running: true},
+ Credential: "valid",
+ BufferBytes: 3 * 1024 * 1024,
+ })
+ for _, want := range []string{"connected to Asymptote Test as device dev-1", "forwarder loaded=true running=true", "credential valid", "buffer 3.0 MiB"} {
+ if !strings.Contains(connected, want) {
+ t.Fatalf("connected line missing %q: %s", want, connected)
+ }
+ }
+ revoked := managedIngestStatusLine(asymptote.ManagedIngestStatus{Enabled: true, DeviceID: "dev-1", Credential: "revoked"})
+ if !strings.Contains(revoked, "credential revoked") || !strings.Contains(revoked, "re-enroll") {
+ t.Fatalf("revoked line = %q", revoked)
+ }
+ unknown := managedIngestStatusLine(asymptote.ManagedIngestStatus{Enabled: true, DeviceID: "dev-1", Credential: "unknown", CredentialMessage: "ingest service unreachable"})
+ if !strings.Contains(unknown, "credential unknown (ingest service unreachable)") {
+ t.Fatalf("unknown line = %q", unknown)
+ }
+ if strings.Contains(connected+revoked+unknown, "bcn_device") {
+ t.Fatal("status lines must never carry a device key")
+ }
+}
+
+func TestHumanBytes(t *testing.T) {
+ cases := map[int64]string{0: "0 B", 512: "512 B", 1024: "1.0 KiB", 1536: "1.5 KiB", 536870912: "512.0 MiB"}
+ for in, want := range cases {
+ if got := humanBytes(in); got != want {
+ t.Errorf("humanBytes(%d) = %q, want %q", in, got, want)
+ }
+ }
+}
diff --git a/cli/beacon/cmd/endpoint_install.go b/cli/beacon/cmd/endpoint_install.go
index 530510c7..84026fea 100644
--- a/cli/beacon/cmd/endpoint_install.go
+++ b/cli/beacon/cmd/endpoint_install.go
@@ -172,6 +172,7 @@ func runEndpointStatus(cmd *cobra.Command, args []string) error {
} else {
fmt.Println("Last event: present")
}
+ fmt.Println(managedIngestStatusLine(status.ManagedIngest))
return nil
}
diff --git a/cli/beacon/internal/auth/auth_test.go b/cli/beacon/internal/auth/auth_test.go
index 6d4ee263..35a0f5b6 100644
--- a/cli/beacon/internal/auth/auth_test.go
+++ b/cli/beacon/internal/auth/auth_test.go
@@ -1,332 +1,214 @@
package auth
import (
+ "context"
"crypto/sha256"
"encoding/base64"
- "encoding/json"
+ "errors"
+ "fmt"
+ "io"
"net/http"
"net/http/httptest"
- "net/url"
- "os"
- "path/filepath"
- "regexp"
- "strconv"
"strings"
"testing"
"time"
)
func TestGeneratePKCECreatesVerifierChallengeAndState(t *testing.T) {
- params, err := GeneratePKCE()
+ p, err := GeneratePKCE()
if err != nil {
t.Fatalf("GeneratePKCE returned error: %v", err)
}
- base64URL := regexp.MustCompile(`^[A-Za-z0-9_-]+$`)
- for name, value := range map[string]string{
- "code verifier": params.CodeVerifier,
- "code challenge": params.CodeChallenge,
- "state": params.State,
- } {
- if len(value) != 43 {
- t.Fatalf("%s length = %d, want 43", name, len(value))
- }
- if !base64URL.MatchString(value) {
- t.Fatalf("%s contains non-base64url characters: %q", name, value)
- }
+ if len(p.CodeVerifier) < 43 || len(p.State) < 43 {
+ t.Fatalf("verifier/state too short: %d/%d", len(p.CodeVerifier), len(p.State))
+ }
+ sum := sha256.Sum256([]byte(p.CodeVerifier))
+ if want := base64.RawURLEncoding.EncodeToString(sum[:]); p.CodeChallenge != want {
+ t.Fatalf("challenge = %q, want S256 of verifier %q", p.CodeChallenge, want)
}
- hash := sha256.Sum256([]byte(params.CodeVerifier))
- wantChallenge := base64.RawURLEncoding.EncodeToString(hash[:])
- if params.CodeChallenge != wantChallenge {
- t.Fatalf("CodeChallenge = %q, want %q", params.CodeChallenge, wantChallenge)
+ other, _ := GeneratePKCE()
+ if other.State == p.State || other.CodeVerifier == p.CodeVerifier {
+ t.Fatal("PKCE values must be random per call")
}
}
-func TestSaveLoadCredentialsPrivatePermissions(t *testing.T) {
- home := t.TempDir()
- t.Setenv("HOME", home)
-
- creds := &Credentials{
- Token: "secret-token",
- TokenPrefix: "asym_123",
- UserID: "user-1",
- Email: "[email protected]",
- OrgName: "Example Org",
- }
- if err := SaveCredentials(creds); err != nil {
- t.Fatalf("SaveCredentials returned error: %v", err)
+func TestCallbackServerRunsExchangeOnceForAValidRedirect(t *testing.T) {
+ var got []string
+ exchange := func(ctx context.Context, code, state, verifier string) error {
+ got = append(got, code+"|"+state+"|"+verifier)
+ return nil
}
- path, err := CredentialsPath()
+ cs, err := NewCallbackServer("state-1", "verifier-1", exchange, 0)
if err != nil {
- t.Fatalf("CredentialsPath returned error: %v", err)
+ t.Fatal(err)
+ }
+ cs.SetSuccessPage("Beacon: device connected", "Close this tab.")
+ cs.Start()
+ defer func() { _ = cs.Shutdown() }()
+ base := fmt.Sprintf("http://127.0.0.1:%d/callback", cs.Port())
+
+ // Wrong state and a missing code are rejected without consuming the flow.
+ for _, q := range []string{"?state=wrong&exchange_code=x", "?state=state-1"} {
+ resp, err := http.Get(base + q)
+ if err != nil {
+ t.Fatal(err)
+ }
+ body, _ := io.ReadAll(resp.Body)
+ resp.Body.Close()
+ if !strings.Contains(string(body), "Authentication Failed") {
+ t.Fatalf("expected failure page for %q, got %s", q, body)
+ }
}
- if got, want := path, filepath.Join(home, ".beacon", "auth", "credentials.json"); got != want {
- t.Fatalf("CredentialsPath = %q, want %q", got, want)
+ if len(got) != 0 {
+ t.Fatalf("exchange must not run for invalid callbacks, ran %d times", len(got))
}
- dirInfo, err := os.Stat(filepath.Dir(path))
+
+ resp, err := http.Get(base + "?state=state-1&exchange_code=code-1")
if err != nil {
- t.Fatalf("stat credentials dir: %v", err)
+ t.Fatal(err)
}
- if got, want := dirInfo.Mode().Perm(), os.FileMode(0700); got != want {
- t.Fatalf("credentials dir permissions = %o, want %o", got, want)
+ body, _ := io.ReadAll(resp.Body)
+ resp.Body.Close()
+ if !strings.Contains(string(body), "Beacon: device connected") || !strings.Contains(string(body), "Close this tab.") {
+ t.Fatalf("expected the custom success page, got %s", body)
}
- fileInfo, err := os.Stat(path)
+ result, err := cs.Wait(2 * time.Second)
if err != nil {
- t.Fatalf("stat credentials file: %v", err)
+ t.Fatal(err)
+ }
+ if result.Error != "" || result.State != "state-1" {
+ t.Fatalf("unexpected result %#v", result)
}
- if got, want := fileInfo.Mode().Perm(), os.FileMode(0600); got != want {
- t.Fatalf("credentials permissions = %o, want %o", got, want)
+ if len(got) != 1 || got[0] != "code-1|state-1|verifier-1" {
+ t.Fatalf("exchange calls = %v", got)
}
- loaded, err := LoadCredentials()
+ // A replayed callback is refused and does not run the exchange again.
+ resp, err = http.Get(base + "?state=state-1&exchange_code=code-2")
if err != nil {
- t.Fatalf("LoadCredentials returned error: %v", err)
+ t.Fatal(err)
}
- if loaded.Token != "secret-token" || loaded.Email != "[email protected]" {
- t.Fatalf("credentials did not round-trip: %#v", loaded)
- }
- if !IsLoggedIn() {
- t.Fatal("IsLoggedIn = false, want true")
+ body, _ = io.ReadAll(resp.Body)
+ resp.Body.Close()
+ if !strings.Contains(string(body), "already handled") || len(got) != 1 {
+ t.Fatalf("replay should be refused; body=%s calls=%d", body, len(got))
}
}
-func TestIsLoggedInRejectsExpiredCredentials(t *testing.T) {
- home := t.TempDir()
- t.Setenv("HOME", home)
-
- if err := SaveCredentials(&Credentials{
- Token: "expired-token",
- UserID: "user-1",
- ExpiresAt: time.Now().Add(-time.Minute),
- }); err != nil {
- t.Fatalf("SaveCredentials returned error: %v", err)
+func TestCallbackServerReportsExchangeFailureToBrowserAndCaller(t *testing.T) {
+ exchange := func(ctx context.Context, code, state, verifier string) error {
+ return errors.New("exchange code has expired; restart enrollment")
}
- if IsLoggedIn() {
- t.Fatal("IsLoggedIn = true, want false for expired credentials")
+ cs, err := NewCallbackServer("s", "v", exchange, 0)
+ if err != nil {
+ t.Fatal(err)
}
-}
-
-func TestIsLoggedInRejectsIncompleteCredentials(t *testing.T) {
- for name, contents := range map[string]string{
- "missing token": `{"token":"","user_id":"user-1"}`,
- "missing user ID": `{"token":"secret-token","user_id":""}`,
- } {
- t.Run(name, func(t *testing.T) {
- home := t.TempDir()
- t.Setenv("HOME", home)
- if _, err := EnsureConfigDir(); err != nil {
- t.Fatalf("EnsureConfigDir returned error: %v", err)
- }
- path, err := CredentialsPath()
- if err != nil {
- t.Fatalf("CredentialsPath returned error: %v", err)
- }
- if err := os.WriteFile(path, []byte(contents), 0600); err != nil {
- t.Fatalf("write credentials: %v", err)
- }
- if IsLoggedIn() {
- t.Fatal("IsLoggedIn = true, want false for incomplete credentials")
- }
- })
+ cs.Start()
+ defer func() { _ = cs.Shutdown() }()
+ resp, err := http.Get(fmt.Sprintf("http://127.0.0.1:%d/callback?state=s&exchange_code=c", cs.Port()))
+ if err != nil {
+ t.Fatal(err)
}
-}
-
-func TestCallbackServerExchangesCodeForToken(t *testing.T) {
- var gotRequest exchangeCodeRequest
- backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- if r.URL.Path != "/api/cli/auth/exchange" {
- t.Fatalf("exchange path = %q, want /api/cli/auth/exchange", r.URL.Path)
- }
- if r.Method != http.MethodPost {
- t.Fatalf("exchange method = %q, want POST", r.Method)
- }
- if err := json.NewDecoder(r.Body).Decode(&gotRequest); err != nil {
- t.Fatalf("decode exchange request: %v", err)
- }
- w.Header().Set("Content-Type", "application/json")
- _, _ = w.Write([]byte(`{"token":"secret-token","token_prefix":"asym_123","user_id":"user-1","email":"[email protected]","org_id":"org-1","org_name":"Example Org"}`))
- }))
- defer backend.Close()
-
- server, err := NewCallbackServer("state-123", "verifier-123", backend.URL, backend.Client())
+ body, _ := io.ReadAll(resp.Body)
+ resp.Body.Close()
+ if !strings.Contains(string(body), "exchange code has expired") {
+ t.Fatalf("browser page should carry the exchange error: %s", body)
+ }
+ result, err := cs.Wait(2 * time.Second)
if err != nil {
- t.Fatalf("NewCallbackServer returned error: %v", err)
+ t.Fatal(err)
}
- defer func() { _ = server.Shutdown() }()
- server.Start()
-
- callbackURL := url.URL{
- Scheme: "http",
- Host: "127.0.0.1:" + strconv.Itoa(server.Port()),
- Path: "/callback",
- RawQuery: "exchange_code=code-123&state=state-123",
- }
- go func() {
- resp, err := http.Get(callbackURL.String())
- if err == nil {
- _ = resp.Body.Close()
- }
- }()
+ if !strings.Contains(result.Error, "exchange code has expired") {
+ t.Fatalf("result = %#v", result)
+ }
+}
- result, err := server.Wait(2 * time.Second)
+func TestCallbackServerErrorQueryEndsTheFlow(t *testing.T) {
+ cs, err := NewCallbackServer("s", "v", func(context.Context, string, string, string) error { return nil }, 0)
if err != nil {
- t.Fatalf("Wait returned error: %v", err)
+ t.Fatal(err)
}
- if result.Error != "" {
- t.Fatalf("callback result error = %q", result.Error)
+ cs.Start()
+ defer func() { _ = cs.Shutdown() }()
+ if _, err := http.Get(fmt.Sprintf("http://127.0.0.1:%d/callback?state=s&error=access_denied", cs.Port())); err != nil {
+ t.Fatal(err)
}
- if result.Token != "secret-token" || result.Email != "[email protected]" || result.OrgName != "Example Org" {
- t.Fatalf("unexpected callback result: %#v", result)
+ result, err := cs.Wait(2 * time.Second)
+ if err != nil {
+ t.Fatal(err)
}
- if gotRequest.ExchangeCode != "code-123" || gotRequest.State != "state-123" || gotRequest.CodeVerifier != "verifier-123" {
- t.Fatalf("unexpected exchange request: %#v", gotRequest)
+ if result.Error != "access_denied" {
+ t.Fatalf("result = %#v", result)
}
}
-func TestCallbackServerWriteTimeoutAllowsDefaultExchangeTimeout(t *testing.T) {
- server, err := NewCallbackServer("state-123", "verifier-123", "https://dashboard.example", nil)
+func TestCallbackServerWaitTimesOut(t *testing.T) {
+ cs, err := NewCallbackServer("s", "v", func(context.Context, string, string, string) error { return nil }, 0)
if err != nil {
- t.Fatalf("NewCallbackServer returned error: %v", err)
+ t.Fatal(err)
}
- defer func() { _ = server.Shutdown() }()
-
- if server.httpClient.Timeout != defaultExchangeTimeout {
- t.Fatalf("default exchange timeout = %s, want %s", server.httpClient.Timeout, defaultExchangeTimeout)
- }
- if server.server.WriteTimeout <= server.httpClient.Timeout {
- t.Fatalf("callback write timeout = %s, want greater than exchange timeout %s", server.server.WriteTimeout, server.httpClient.Timeout)
+ cs.Start()
+ defer func() { _ = cs.Shutdown() }()
+ if _, err := cs.Wait(20 * time.Millisecond); err == nil {
+ t.Fatal("expected a timeout error")
}
}
-func TestLoginRejectsIncompleteExchangeResponse(t *testing.T) {
- for name, tc := range map[string]struct {
- responseBody string
- wantErr string
- }{
- "missing token": {
- responseBody: `{"token":"","token_prefix":"asym_123","user_id":"user-1","email":"[email protected]"}`,
- wantErr: "credentials token is required",
- },
- "missing user ID": {
- responseBody: `{"token":"secret-token","token_prefix":"asym_123","user_id":"","email":"[email protected]"}`,
- wantErr: "credentials user ID is required",
- },
- } {
- t.Run(name, func(t *testing.T) {
- backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- w.Header().Set("Content-Type", "application/json")
- _, _ = w.Write([]byte(tc.responseBody))
- }))
- defer backend.Close()
-
- callbackErr := make(chan error, 1)
- openBrowser := func(authURL string) error {
- u, err := url.Parse(authURL)
- if err != nil {
- return err
- }
- callbackURL := url.URL{
- Scheme: "http",
- Host: "127.0.0.1:" + u.Query().Get("port"),
- Path: "/callback",
- RawQuery: "exchange_code=code-123&state=" + url.QueryEscape(u.Query().Get("state")),
- }
- go func() {
- resp, err := http.Get(callbackURL.String())
- if err == nil {
- _ = resp.Body.Close()
- }
- callbackErr <- err
- }()
- return nil
- }
-
- creds, err := Login(LoginOptions{
- DashboardURL: backend.URL,
- HTTPClient: backend.Client(),
- OpenBrowser: openBrowser,
- Timeout: 2 * time.Second,
- })
- if err == nil {
- t.Fatal("Login error = nil, want error")
- }
- if creds != nil {
- t.Fatalf("Login credentials = %#v, want nil", creds)
- }
- if !strings.Contains(err.Error(), tc.wantErr) {
- t.Fatalf("Login error = %q, want to contain %q", err, tc.wantErr)
- }
- if err := <-callbackErr; err != nil {
- t.Fatalf("callback request failed: %v", err)
- }
- })
+func TestCallbackServerRequiresAnExchangeFunc(t *testing.T) {
+ if _, err := NewCallbackServer("s", "v", nil, 0); err == nil {
+ t.Fatal("expected error for nil exchange")
}
}
-func TestCallbackServerIgnoresInvalidCallbacksBeforeValidRedirect(t *testing.T) {
- backendCalls := 0
- backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- backendCalls++
- if r.URL.Path != "/api/cli/auth/exchange" {
- t.Fatalf("exchange path = %q, want /api/cli/auth/exchange", r.URL.Path)
+func TestPostJSONDecodesSuccessAndSurfacesServerDetail(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Header.Get("Content-Type") != "application/json" || r.Header.Get("User-Agent") != "beacon-cli" {
+ t.Errorf("unexpected headers %v", r.Header)
}
- w.Header().Set("Content-Type", "application/json")
- _, _ = w.Write([]byte(`{"token":"secret-token","token_prefix":"asym_123","user_id":"user-1","email":"[email protected]","org_id":"org-1","org_name":"Example Org"}`))
- }))
- defer backend.Close()
-
- server, err := NewCallbackServer("expected-state", "verifier-123", backend.URL, backend.Client())
- if err != nil {
- t.Fatalf("NewCallbackServer returned error: %v", err)
- }
- defer func() { _ = server.Shutdown() }()
- server.Start()
-
- baseURL := "http://127.0.0.1:" + strconv.Itoa(server.Port()) + "/callback"
- for _, rawURL := range []string{
- baseURL + "?exchange_code=code&state=wrong-state",
- baseURL + "?state=expected-state",
- baseURL + "?error=access_denied",
- } {
- resp, err := http.Get(rawURL)
- if err == nil {
- _ = resp.Body.Close()
+ switch r.URL.Path {
+ case "/ok":
+ w.WriteHeader(http.StatusCreated)
+ _, _ = w.Write([]byte(`{"state":"abc"}`))
+ case "/detail":
+ w.WriteHeader(http.StatusGone)
+ _, _ = w.Write([]byte(`{"detail":"exchange code has expired; restart enrollment"}`))
+ default:
+ w.WriteHeader(http.StatusBadGateway)
+ _, _ = w.Write([]byte("upstream down"))
}
- }
- if backendCalls != 0 {
- t.Fatalf("backend calls after invalid callbacks = %d, want 0", backendCalls)
- }
-
- resp, err := http.Get(baseURL + "?exchange_code=code-123&state=expected-state")
- if err != nil {
- t.Fatalf("valid callback request failed: %v", err)
- }
- _ = resp.Body.Close()
+ }))
+ defer server.Close()
- result, err := server.Wait(2 * time.Second)
- if err != nil {
- t.Fatalf("Wait returned error: %v", err)
+ var out struct {
+ State string `json:"state"`
}
- if result.Error != "" {
- t.Fatalf("callback result error = %q", result.Error)
+ if err := PostJSON(context.Background(), server.Client(), server.URL+"/ok", map[string]string{"a": "b"}, &out); err != nil || out.State != "abc" {
+ t.Fatalf("PostJSON ok: err=%v out=%+v", err, out)
}
- if result.Token != "secret-token" || result.State != "expected-state" {
- t.Fatalf("unexpected callback result: %#v", result)
+ err := PostJSON(context.Background(), server.Client(), server.URL+"/detail", map[string]string{}, nil)
+ var httpErr *HTTPError
+ if !errors.As(err, &httpErr) || httpErr.Status != http.StatusGone || err.Error() != "exchange code has expired; restart enrollment" {
+ t.Fatalf("expected a 410 HTTPError with the server detail, got %v", err)
}
- if backendCalls != 1 {
- t.Fatalf("backend calls = %d, want 1", backendCalls)
+ err = PostJSON(context.Background(), server.Client(), server.URL+"/plain", map[string]string{}, nil)
+ if !errors.As(err, &httpErr) || httpErr.Status != http.StatusBadGateway || !strings.Contains(err.Error(), "upstream down") {
+ t.Fatalf("expected a 502 HTTPError with the raw body, got %v", err)
}
}
func TestResolveDashboardURL(t *testing.T) {
t.Setenv(DashboardURLEnv, "")
if got := ResolveDashboardURL(""); got != DefaultDashboardURL {
- t.Fatalf("ResolveDashboardURL empty = %q, want default", got)
+ t.Fatalf("default = %q", got)
+ }
+ if got := ResolveDashboardURL(" https://dash.example.test/ "); got != "https://dash.example.test" {
+ t.Fatalf("flag = %q", got)
}
- t.Setenv(DashboardURLEnv, "https://env.example/")
- if got := ResolveDashboardURL(""); got != "https://env.example" {
- t.Fatalf("ResolveDashboardURL env = %q, want env without trailing slash", got)
+ t.Setenv(DashboardURLEnv, "https://env.example.test/")
+ if got := ResolveDashboardURL(""); got != "https://env.example.test" {
+ t.Fatalf("env = %q", got)
}
- if got := ResolveDashboardURL("https://flag.example///"); got != "https://flag.example" {
- t.Fatalf("ResolveDashboardURL flag = %q, want flag without trailing slash", got)
+ if got := ResolveDashboardURL("https://flag.example.test"); got != "https://flag.example.test" {
+ t.Fatalf("flag should win over env, got %q", got)
}
}
diff --git a/cli/beacon/internal/auth/credentials.go b/cli/beacon/internal/auth/credentials.go
deleted file mode 100644
index 979a620f..00000000
--- a/cli/beacon/internal/auth/credentials.go
+++ /dev/null
@@ -1,167 +0,0 @@
-package auth
-
-import (
- "encoding/json"
- "fmt"
- "os"
- "path/filepath"
- "strings"
- "time"
-)
-
-const (
- ConfigDirName = ".beacon"
- AuthDirName = "auth"
- CredentialsFileName = "credentials.json"
-)
-
-type Credentials struct {
- Token string `json:"token"`
- TokenPrefix string `json:"token_prefix"`
- ExpiresAt time.Time `json:"expires_at"`
- UserID string `json:"user_id"`
- Email string `json:"email,omitempty"`
- OrgID string `json:"org_id,omitempty"`
- OrgName string `json:"org_name,omitempty"`
-}
-
-func ConfigDir() (string, error) {
- home, err := os.UserHomeDir()
- if err != nil {
- return "", err
- }
- return filepath.Join(home, ConfigDirName, AuthDirName), nil
-}
-
-func EnsureConfigDir() (string, error) {
- dir, err := ConfigDir()
- if err != nil {
- return "", err
- }
- if err := os.MkdirAll(dir, 0700); err != nil {
- return "", err
- }
- return dir, nil
-}
-
-func CredentialsPath() (string, error) {
- dir, err := ConfigDir()
- if err != nil {
- return "", err
- }
- return filepath.Join(dir, CredentialsFileName), nil
-}
-
-func SaveCredentials(creds *Credentials) error {
- if creds == nil {
- return fmt.Errorf("credentials are required")
- }
- if err := creds.validateRequiredFields(); err != nil {
- return err
- }
- if _, err := EnsureConfigDir(); err != nil {
- return fmt.Errorf("failed to create auth directory: %w", err)
- }
- path, err := CredentialsPath()
- if err != nil {
- return fmt.Errorf("failed to resolve credentials path: %w", err)
- }
- data, err := json.MarshalIndent(creds, "", " ")
- if err != nil {
- return fmt.Errorf("failed to marshal credentials: %w", err)
- }
- if err := os.WriteFile(path, data, 0600); err != nil {
- return fmt.Errorf("failed to write credentials: %w", err)
- }
- return os.Chmod(path, 0600)
-}
-
-func LoadCredentials() (*Credentials, error) {
- path, err := CredentialsPath()
- if err != nil {
- return nil, fmt.Errorf("failed to resolve credentials path: %w", err)
- }
- data, err := os.ReadFile(path)
- if err != nil {
- if os.IsNotExist(err) {
- return nil, nil
- }
- return nil, fmt.Errorf("failed to read credentials: %w", err)
- }
- var creds Credentials
- if err := json.Unmarshal(data, &creds); err != nil {
- return nil, fmt.Errorf("failed to parse credentials: %w", err)
- }
- return &creds, nil
-}
-
-func DeleteCredentials() error {
- path, err := CredentialsPath()
- if err != nil {
- return fmt.Errorf("failed to resolve credentials path: %w", err)
- }
- if err := os.Remove(path); err != nil {
- if os.IsNotExist(err) {
- return nil
- }
- return fmt.Errorf("failed to delete credentials: %w", err)
- }
- return nil
-}
-
-func IsLoggedIn() bool {
- creds, err := LoadCredentials()
- if err != nil || creds == nil {
- return false
- }
- return creds.validateRequiredFields() == nil && !creds.IsExpired()
-}
-
-func (c *Credentials) validateRequiredFields() error {
- if c == nil {
- return fmt.Errorf("credentials are required")
- }
- if strings.TrimSpace(c.Token) == "" {
- return fmt.Errorf("credentials token is required")
- }
- if strings.TrimSpace(c.UserID) == "" {
- return fmt.Errorf("credentials user ID is required")
- }
- return nil
-}
-
-func (c *Credentials) IsExpired() bool {
- if c == nil || c.ExpiresAt.IsZero() {
- return false
- }
- return time.Now().After(c.ExpiresAt)
-}
-
-func (c *Credentials) ExpiresIn() string {
- if c == nil || c.ExpiresAt.IsZero() {
- return "never"
- }
- if c.IsExpired() {
- return "expired"
- }
- duration := time.Until(c.ExpiresAt)
- days := int(duration.Hours() / 24)
- if days > 1 {
- return fmt.Sprintf("%d days", days)
- }
- if days == 1 {
- return "1 day"
- }
- hours := int(duration.Hours())
- if hours > 1 {
- return fmt.Sprintf("%d hours", hours)
- }
- if hours == 1 {
- return "1 hour"
- }
- minutes := int(duration.Minutes())
- if minutes > 1 {
- return fmt.Sprintf("%d minutes", minutes)
- }
- return "less than a minute"
-}
diff --git a/cli/beacon/internal/auth/dashboard.go b/cli/beacon/internal/auth/dashboard.go
new file mode 100644
index 00000000..47a7763c
--- /dev/null
+++ b/cli/beacon/internal/auth/dashboard.go
@@ -0,0 +1,119 @@
+// Package auth holds the browser-based PKCE handshake Beacon uses to obtain a
+// credential from the Asymptote dashboard: PKCE parameter generation, the
+// loopback callback server the dashboard redirects to, the browser opener, and
+// small helpers for talking to the dashboard's API.
+//
+// The package is deliberately flow-agnostic. It knows how to run one PKCE
+// round trip; what is exchanged at the end (today, a per-device ingest key for
+// `beacon endpoint connect`) is supplied by the caller as an ExchangeFunc.
+package auth
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "os"
+ "strings"
+ "time"
+)
+
+const (
+ DefaultDashboardURL = "https://asymptotelabs.ai"
+ DashboardURLEnv = "BEACON_DASHBOARD_URL"
+ // AuthTimeout bounds how long a command waits for the browser step.
+ AuthTimeout = 5 * time.Minute
+)
+
+// ResolveDashboardURL picks the dashboard base URL from a flag, the environment,
+// or the default, in that order, without a trailing slash.
+func ResolveDashboardURL(flagValue string) string {
+ if flagValue != "" {
+ return NormalizeDashboardURL(flagValue)
+ }
+ if envValue := os.Getenv(DashboardURLEnv); envValue != "" {
+ return NormalizeDashboardURL(envValue)
+ }
+ return DefaultDashboardURL
+}
+
+// NormalizeDashboardURL trims whitespace and trailing slashes, falling back to the
+// default for an empty value.
+func NormalizeDashboardURL(raw string) string {
+ raw = strings.TrimSpace(raw)
+ if raw == "" {
+ raw = DefaultDashboardURL
+ }
+ return strings.TrimRight(raw, "/")
+}
+
+// PostJSON sends body as JSON to url and decodes a 2xx response into out. Error
+// responses are reduced to the dashboard's `detail` or `error` text when present,
+// so callers can show the server's own explanation.
+func PostJSON(ctx context.Context, client *http.Client, url string, body any, out any) error {
+ if client == nil {
+ client = &http.Client{Timeout: 30 * time.Second}
+ }
+ payload, err := json.Marshal(body)
+ if err != nil {
+ return fmt.Errorf("failed to marshal request: %w", err)
+ }
+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(payload))
+ if err != nil {
+ return fmt.Errorf("failed to create request: %w", err)
+ }
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("Accept", "application/json")
+ req.Header.Set("User-Agent", "beacon-cli")
+
+ resp, err := client.Do(req)
+ if err != nil {
+ return fmt.Errorf("request to %s failed: %w", url, err)
+ }
+ defer resp.Body.Close()
+ respBody, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
+ if err != nil {
+ return fmt.Errorf("failed to read response: %w", err)
+ }
+ if resp.StatusCode < 200 || resp.StatusCode > 299 {
+ return &HTTPError{Status: resp.StatusCode, Detail: errorDetail(respBody)}
+ }
+ if out == nil {
+ return nil
+ }
+ if err := json.Unmarshal(respBody, out); err != nil {
+ return fmt.Errorf("failed to parse response: %w", err)
+ }
+ return nil
+}
+
+// HTTPError is a non-2xx dashboard response.
+type HTTPError struct {
+ Status int
+ Detail string
+}
+
+func (e *HTTPError) Error() string {
+ if e.Detail != "" {
+ return e.Detail
+ }
+ return fmt.Sprintf("request failed with status %d", e.Status)
+}
+
+func errorDetail(body []byte) string {
+ var errResp struct {
+ Detail string `json:"detail"`
+ Error string `json:"error"`
+ }
+ if json.Unmarshal(body, &errResp) == nil {
+ if errResp.Detail != "" {
+ return errResp.Detail
+ }
+ if errResp.Error != "" {
+ return errResp.Error
+ }
+ }
+ return strings.TrimSpace(string(body))
+}
diff --git a/cli/beacon/internal/auth/login.go b/cli/beacon/internal/auth/login.go
deleted file mode 100644
index b2703d08..00000000
--- a/cli/beacon/internal/auth/login.go
+++ /dev/null
@@ -1,127 +0,0 @@
-package auth
-
-import (
- "fmt"
- "io"
- "net/http"
- "net/url"
- "os"
- "strings"
- "time"
-)
-
-const (
- DefaultDashboardURL = "https://asymptotelabs.ai"
- DashboardURLEnv = "BEACON_DASHBOARD_URL"
- AuthTimeout = 5 * time.Minute
-)
-
-type LoginOptions struct {
- DashboardURL string
- OpenBrowser func(string) error
- HTTPClient *http.Client
- Out io.Writer
- Timeout time.Duration
-}
-
-func Login(opts LoginOptions) (*Credentials, error) {
- dashboardURL := ResolveDashboardURL(opts.DashboardURL)
- timeout := opts.Timeout
- if timeout == 0 {
- timeout = AuthTimeout
- }
- openBrowser := opts.OpenBrowser
- if openBrowser == nil {
- openBrowser = OpenBrowser
- }
- out := opts.Out
- if out == nil {
- out = io.Discard
- }
-
- pkce, err := GeneratePKCE()
- if err != nil {
- return nil, fmt.Errorf("failed to generate PKCE parameters: %w", err)
- }
- server, err := NewCallbackServer(pkce.State, pkce.CodeVerifier, dashboardURL, opts.HTTPClient)
- if err != nil {
- return nil, err
- }
- defer func() {
- _ = server.Shutdown()
- }()
- server.Start()
-
- authURL, err := buildAuthURL(dashboardURL, pkce.CodeChallenge, pkce.State, server.Port())
- if err != nil {
- return nil, err
- }
- fmt.Fprintf(out, "Opening browser to %s/cli/auth...\n", dashboardURL)
- if err := openBrowser(authURL); err != nil {
- fmt.Fprintln(out, "Failed to open browser automatically.")
- fmt.Fprintf(out, "Please open this URL in your browser:\n%s\n", authURL)
- }
- fmt.Fprintln(out, "Waiting for authentication...")
-
- result, err := server.Wait(timeout)
- if err != nil {
- return nil, err
- }
- if result.Error != "" {
- return nil, fmt.Errorf("authentication failed: %s", result.Error)
- }
- var expiresAt time.Time
- if result.ExpiresAt != "" {
- expiresAt, err = time.Parse(time.RFC3339, result.ExpiresAt)
- if err != nil {
- expiresAt, err = time.Parse("2006-01-02T15:04:05", result.ExpiresAt)
- if err != nil {
- return nil, fmt.Errorf("failed to parse expiration time: %w", err)
- }
- }
- }
- creds := &Credentials{
- Token: result.Token,
- TokenPrefix: result.TokenPrefix,
- ExpiresAt: expiresAt,
- UserID: result.UserID,
- Email: result.Email,
- OrgID: result.OrgID,
- OrgName: result.OrgName,
- }
- if err := creds.validateRequiredFields(); err != nil {
- return nil, fmt.Errorf("invalid authentication response: %w", err)
- }
- return creds, nil
-}
-
-func ResolveDashboardURL(flagValue string) string {
- if flagValue != "" {
- return normalizeDashboardURL(flagValue)
- }
- if envValue := os.Getenv(DashboardURLEnv); envValue != "" {
- return normalizeDashboardURL(envValue)
- }
- return DefaultDashboardURL
-}
-
-func buildAuthURL(dashboardURL, codeChallenge, state string, port int) (string, error) {
- u, err := url.Parse(normalizeDashboardURL(dashboardURL) + "/cli/auth")
- if err != nil {
- return "", fmt.Errorf("failed to parse dashboard URL: %w", err)
- }
- q := u.Query()
- q.Set("code_challenge", codeChallenge)
- q.Set("state", state)
- q.Set("port", fmt.Sprintf("%d", port))
- u.RawQuery = q.Encode()
- return u.String(), nil
-}
-
-func normalizeDashboardURL(raw string) string {
- raw = strings.TrimSpace(raw)
- if raw == "" {
- raw = DefaultDashboardURL
- }
- return strings.TrimRight(raw, "/")
-}
diff --git a/cli/beacon/internal/auth/server.go b/cli/beacon/internal/auth/server.go
index a4bb89d7..c6c4ee56 100644
--- a/cli/beacon/internal/auth/server.go
+++ b/cli/beacon/internal/auth/server.go
@@ -1,15 +1,11 @@
package auth
import (
- "bytes"
"context"
- "encoding/json"
"fmt"
"html"
- "io"
"net"
"net/http"
- "strings"
"sync"
"time"
)
@@ -20,34 +16,21 @@ const (
callbackWriteTimeoutSlack = 5 * time.Second
)
-type CallbackResult struct {
- Token string
- TokenPrefix string
- ExpiresAt string
- UserID string
- Email string
- OrgID string
- OrgName string
- State string
- Error string
-}
-
-type exchangeCodeRequest struct {
- ExchangeCode string `json:"exchange_code"`
- State string `json:"state"`
- CodeVerifier string `json:"code_verifier"`
-}
+// ExchangeFunc redeems the one-time code the dashboard delivered to the callback.
+// It runs inside the callback request, so the browser sees the outcome; the
+// caller keeps whatever the exchange returned in its own closure.
+type ExchangeFunc func(ctx context.Context, exchangeCode, state, codeVerifier string) error
-type exchangeCodeResponse struct {
- Token string `json:"token"`
- TokenPrefix string `json:"token_prefix"`
- ExpiresAt *string `json:"expires_at"`
- UserID string `json:"user_id"`
- Email string `json:"email"`
- OrgID string `json:"org_id"`
- OrgName string `json:"org_name"`
+// CallbackResult is what Wait returns: the state that completed the flow, or the
+// error that ended it.
+type CallbackResult struct {
+ State string
+ Error string
}
+// CallbackServer is the loopback HTTP server the dashboard redirects to with the
+// exchange code. It listens on an ephemeral 127.0.0.1 port, accepts exactly one
+// valid callback, and runs the ExchangeFunc before answering the browser.
type CallbackServer struct {
port int
listener net.Listener
@@ -57,17 +40,24 @@ type CallbackServer struct {
completed bool
state string
codeVerifier string
- dashboardURL string
- httpClient *http.Client
+ exchange ExchangeFunc
+ successTitle string
+ successBody string
}
-func NewCallbackServer(expectedState, codeVerifier, dashboardURL string, httpClient *http.Client) (*CallbackServer, error) {
+// NewCallbackServer binds the loopback listener. exchangeTimeout should match the
+// timeout of the HTTP client the ExchangeFunc uses so the browser response is not
+// cut off before the exchange finishes; zero uses a 30 s default.
+func NewCallbackServer(expectedState, codeVerifier string, exchange ExchangeFunc, exchangeTimeout time.Duration) (*CallbackServer, error) {
+ if exchange == nil {
+ return nil, fmt.Errorf("callback server needs an exchange function")
+ }
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
return nil, fmt.Errorf("failed to start callback server: %w", err)
}
- if httpClient == nil {
- httpClient = &http.Client{Timeout: defaultExchangeTimeout}
+ if exchangeTimeout <= 0 {
+ exchangeTimeout = defaultExchangeTimeout
}
cs := &CallbackServer{
port: listener.Addr().(*net.TCPAddr).Port,
@@ -75,8 +65,9 @@ func NewCallbackServer(expectedState, codeVerifier, dashboardURL string, httpCli
resultCh: make(chan *CallbackResult, 1),
state: expectedState,
codeVerifier: codeVerifier,
- dashboardURL: normalizeDashboardURL(dashboardURL),
- httpClient: httpClient,
+ exchange: exchange,
+ successTitle: "Beacon Authentication Complete",
+ successBody: "You can close this window and return to the terminal.",
}
mux := http.NewServeMux()
mux.HandleFunc("/callback", cs.handleCallback)
@@ -84,23 +75,27 @@ func NewCallbackServer(expectedState, codeVerifier, dashboardURL string, httpCli
Handler: mux,
ReadHeaderTimeout: callbackReadTimeout,
ReadTimeout: callbackReadTimeout,
- WriteTimeout: callbackWriteTimeout(httpClient),
+ WriteTimeout: exchangeTimeout + callbackWriteTimeoutSlack,
}
return cs, nil
}
-func callbackWriteTimeout(httpClient *http.Client) time.Duration {
- exchangeTimeout := defaultExchangeTimeout
- if httpClient != nil && httpClient.Timeout > exchangeTimeout {
- exchangeTimeout = httpClient.Timeout
+// SetSuccessPage customizes what the browser shows after a successful exchange.
+func (cs *CallbackServer) SetSuccessPage(title, body string) {
+ if title != "" {
+ cs.successTitle = title
+ }
+ if body != "" {
+ cs.successBody = body
}
- return exchangeTimeout + callbackWriteTimeoutSlack
}
+// Port is the ephemeral loopback port the dashboard must redirect to.
func (cs *CallbackServer) Port() int {
return cs.port
}
+// Start serves in the background until Shutdown.
func (cs *CallbackServer) Start() {
go func() {
if err := cs.server.Serve(cs.listener); err != nil && err != http.ErrServerClosed {
@@ -109,15 +104,17 @@ func (cs *CallbackServer) Start() {
}()
}
+// Wait blocks for the first completed callback or the timeout.
func (cs *CallbackServer) Wait(timeout time.Duration) (*CallbackResult, error) {
select {
case result := <-cs.resultCh:
return result, nil
case <-time.After(timeout):
- return nil, fmt.Errorf("timeout waiting for authentication callback")
+ return nil, fmt.Errorf("timeout waiting for the browser to finish")
}
}
+// Shutdown stops the listener.
func (cs *CallbackServer) Shutdown() error {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
@@ -141,35 +138,22 @@ func (cs *CallbackServer) handleCallback(w http.ResponseWriter, r *http.Request)
return
}
if !cs.reserveCompletion() {
- cs.sendResponse(w, false, "Authentication callback already handled")
+ cs.sendResponse(w, false, "Callback already handled")
return
}
- tokenResp, err := cs.exchangeCodeForToken(r.Context(), exchangeCode, state, cs.codeVerifier)
- if err != nil {
+ if err := cs.exchange(r.Context(), exchangeCode, state, cs.codeVerifier); err != nil {
message := fmt.Sprintf("failed to exchange code: %v", err)
cs.resultCh <- &CallbackResult{Error: message}
cs.sendResponse(w, false, message)
return
}
- result := &CallbackResult{
- Token: tokenResp.Token,
- TokenPrefix: tokenResp.TokenPrefix,
- UserID: tokenResp.UserID,
- Email: tokenResp.Email,
- OrgID: tokenResp.OrgID,
- OrgName: tokenResp.OrgName,
- State: state,
- }
- if tokenResp.ExpiresAt != nil {
- result.ExpiresAt = *tokenResp.ExpiresAt
- }
- cs.resultCh <- result
+ cs.resultCh <- &CallbackResult{State: state}
cs.sendResponse(w, true, "")
}
func (cs *CallbackServer) finishCallback(w http.ResponseWriter, result *CallbackResult, success bool, errorMsg string) {
if !cs.reserveCompletion() {
- cs.sendResponse(w, false, "Authentication callback already handled")
+ cs.sendResponse(w, false, "Callback already handled")
return
}
cs.resultCh <- result
@@ -186,66 +170,18 @@ func (cs *CallbackServer) reserveCompletion() bool {
return true
}
-func (cs *CallbackServer) exchangeCodeForToken(ctx context.Context, exchangeCode, state, codeVerifier string) (*exchangeCodeResponse, error) {
- bodyBytes, err := json.Marshal(exchangeCodeRequest{
- ExchangeCode: exchangeCode,
- State: state,
- CodeVerifier: codeVerifier,
- })
- if err != nil {
- return nil, fmt.Errorf("failed to marshal request: %w", err)
- }
- req, err := http.NewRequestWithContext(ctx, http.MethodPost, cs.dashboardURL+"/api/cli/auth/exchange", bytes.NewReader(bodyBytes))
- if err != nil {
- return nil, fmt.Errorf("failed to create exchange request: %w", err)
- }
- req.Header.Set("Content-Type", "application/json")
- req.Header.Set("Accept", "application/json")
- req.Header.Set("User-Agent", "beacon-cli")
-
- resp, err := cs.httpClient.Do(req)
- if err != nil {
- return nil, fmt.Errorf("failed to call exchange endpoint: %w", err)
- }
- defer resp.Body.Close()
- respBody, err := io.ReadAll(resp.Body)
- if err != nil {
- return nil, fmt.Errorf("failed to read exchange response: %w", err)
- }
- if resp.StatusCode != http.StatusOK {
- var errResp struct {
- Detail string `json:"detail"`
- Error string `json:"error"`
- }
- if json.Unmarshal(respBody, &errResp) == nil {
- if errResp.Detail != "" {
- return nil, fmt.Errorf("%s", errResp.Detail)
- }
- if errResp.Error != "" {
- return nil, fmt.Errorf("%s", errResp.Error)
- }
- }
- return nil, fmt.Errorf("exchange failed with status %d: %s", resp.StatusCode, strings.TrimSpace(string(respBody)))
- }
- var tokenResp exchangeCodeResponse
- if err := json.Unmarshal(respBody, &tokenResp); err != nil {
- return nil, fmt.Errorf("failed to parse exchange response: %w", err)
- }
- return &tokenResp, nil
-}
-
func (cs *CallbackServer) sendResponse(w http.ResponseWriter, success bool, errorMsg string) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Header().Set("Cache-Control", "no-store")
if success {
- _, _ = w.Write([]byte(`<!DOCTYPE html>
+ _, _ = fmt.Fprintf(w, `<!DOCTYPE html>
<html>
-<head><title>Beacon Login Complete</title></head>
+<head><title>%s</title></head>
<body>
- <h1>Authentication Successful</h1>
- <p>You can close this window and return to the terminal.</p>
+ <h1>%s</h1>
+ <p>%s</p>
</body>
-</html>`))
+</html>`, html.EscapeString(cs.successTitle), html.EscapeString(cs.successTitle), html.EscapeString(cs.successBody))
return
}
_, _ = fmt.Fprintf(w, `<!DOCTYPE html>
diff --git a/cli/beacon/internal/endpoint/asymptote/connect.go b/cli/beacon/internal/endpoint/asymptote/connect.go
new file mode 100644
index 00000000..bc756f0e
--- /dev/null
+++ b/cli/beacon/internal/endpoint/asymptote/connect.go
@@ -0,0 +1,294 @@
+package asymptote
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "io"
+ "os"
+ "path/filepath"
+ "time"
+
+ endpointconfig "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/config"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/service"
+)
+
+// Forwarder is the service-manager surface Connect and Disconnect need. service.ForwarderManager
+// is the production implementation; tests supply a fake so no launchctl or systemctl runs.
+type Forwarder interface {
+ Supported() bool
+ UnsupportedReason() string
+ Label() string
+ WriteUnit(vectorBin, configPath string) (string, error)
+ Load() error
+ Unload() error
+ RemoveUnits()
+ Status() service.Status
+}
+
+// ConnectOptions drives Connect.
+type ConnectOptions struct {
+ UserMode bool
+ // LogPath is the runtime log Vector tails; the inventory log is derived from it.
+ LogPath string
+ // VectorBin overrides Vector discovery.
+ VectorBin string
+ // Forwarder overrides the service manager; nil uses service.ForwarderManager.
+ Forwarder Forwarder
+ // Enroll is the browser flow; the CLI fills Device, DashboardURL, browser opener.
+ Enroll EnrollOptions
+ // InstallID identifies this machine across re-enrollments. Empty reuses the stored
+ // enrollment's id or mints a new one.
+ InstallID string
+ Out io.Writer
+ // Now is injectable for tests.
+ Now func() time.Time
+}
+
+// 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
+}
+
+// Connect enrolls this machine and starts the forwarder.
+//
+// Failure ordering is deliberate: Vector is located before the browser opens, so a machine
+// without Vector never mints a key it cannot use; the key is written to the 0600 secrets file
+// before the config that references it; the config is validated before a service unit points at
+// it; and the enrollment record is saved last, so status never claims a connection that did not
+// finish. A re-run on an enrolled machine reuses its install id, which rotates the key in place
+// on the server rather than creating a second device.
+func Connect(ctx context.Context, opts ConnectOptions) (*ConnectResult, error) {
+ out := opts.Out
+ if out == nil {
+ out = io.Discard
+ }
+ now := opts.Now
+ if now == nil {
+ now = time.Now
+ }
+ manager := opts.Forwarder
+ if manager == nil {
+ manager = service.ForwarderManager{UserMode: opts.UserMode}
+ }
+ if !manager.Supported() {
+ return nil, errors.New(manager.UnsupportedReason())
+ }
+ vector, err := FindVector(opts.VectorBin)
+ if err != nil {
+ return nil, err
+ }
+ fmt.Fprintf(out, "Using Vector %s at %s\n", vector.Version, vector.Path)
+
+ previous, err := LoadEnrollment(opts.UserMode)
+ if err != nil && !errors.Is(err, ErrNotEnrolled) {
+ return nil, err
+ }
+ installID := opts.InstallID
+ if installID == "" && previous != nil {
+ installID = previous.InstallID
+ }
+ if installID == "" {
+ installID, err = newInstallID()
+ if err != nil {
+ return nil, err
+ }
+ }
+ enrollOpts := opts.Enroll
+ enrollOpts.Device.InstallID = installID
+ if enrollOpts.Device.InstallMode == "" {
+ enrollOpts.Device.InstallMode = installMode(opts.UserMode)
+ }
+ if enrollOpts.Out == nil {
+ enrollOpts.Out = out
+ }
+
+ result, err := Enroll(ctx, enrollOpts)
+ if err != nil {
+ return nil, err
+ }
+ fmt.Fprintf(out, "Approved for %s (device %s, key %s)\n", displayOrg(result), result.DeviceID, result.KeyPrefix)
+
+ // Secrets first, then the config that references them, then the unit that runs it.
+ if err := WriteSecrets(opts.UserMode, result.DeviceKey); err != nil {
+ return nil, fmt.Errorf("could not store the device key: %w", err)
+ }
+ result.DeviceKey = ""
+ dataDir := DataDir(opts.UserMode)
+ if err := os.MkdirAll(dataDir, 0o700); err != nil {
+ return nil, err
+ }
+ logPath := opts.LogPath
+ if logPath == "" {
+ logPath = endpointconfig.Default(opts.UserMode, "").LogPath
+ }
+ rendered, err := RenderVectorConfig(RenderOptions{
+ LogPath: logPath,
+ IngestURL: result.IngestURL,
+ SecretsFile: SecretsPath(opts.UserMode),
+ DataDir: dataDir,
+ })
+ if err != nil {
+ return nil, err
+ }
+ configPath := VectorConfigPath(opts.UserMode)
+ if err := writeFileAtomic(configPath, []byte(rendered), 0o644); err != nil {
+ return nil, err
+ }
+ if err := ValidateVectorConfig(vector.Path, configPath); err != nil {
+ return nil, err
+ }
+ unitPath, err := manager.WriteUnit(vector.Path, configPath)
+ if err != nil {
+ return nil, err
+ }
+ if err := manager.Load(); err != nil {
+ return nil, fmt.Errorf("forwarder installed at %s but could not be started: %w", unitPath, err)
+ }
+
+ enrollment := Enrollment{
+ InstallID: installID,
+ IngestURL: result.IngestURL,
+ DashboardURL: enrollDashboardURL(enrollOpts.DashboardURL),
+ DeviceID: result.DeviceID,
+ KeyPrefix: result.KeyPrefix,
+ OrganizationID: result.OrganizationID,
+ OrganizationName: result.OrganizationName,
+ Email: result.Email,
+ EnrolledAt: now().UTC(),
+ VectorBin: vector.Path,
+ VectorVersion: vector.Version,
+ }
+ if result.ExpiresAt != nil {
+ enrollment.ExpiresAt = *result.ExpiresAt
+ }
+ if err := SaveEnrollment(opts.UserMode, enrollment); err != nil {
+ return nil, err
+ }
+ if err := updateConfig(opts.UserMode, logPath, &endpointconfig.ManagedIngest{
+ Enabled: true,
+ IngestURL: result.IngestURL,
+ DeviceID: result.DeviceID,
+ OrganizationID: result.OrganizationID,
+ }); err != nil {
+ return nil, err
+ }
+ return &ConnectResult{
+ Enrollment: enrollment,
+ VectorConfig: configPath,
+ SecretsFile: SecretsPath(opts.UserMode),
+ UnitPath: unitPath,
+ Forwarder: manager.Label(),
+ ReEnrolled: previous != nil,
+ ForwarderState: manager.Status(),
+ }, nil
+}
+
+// DisconnectOptions drives Disconnect.
+type DisconnectOptions struct {
+ UserMode bool
+ LogPath string
+ // Forwarder overrides the service manager; nil uses service.ForwarderManager.
+ Forwarder Forwarder
+ // KeepCredentials leaves enrollment.json and the secrets file in place.
+ KeepCredentials bool
+}
+
+// Disconnect stops and removes the forwarder and, unless asked to keep them, the local
+// credentials. Nothing is revoked server-side: that is done from the dashboard's Beacon
+// Endpoints page, and the CLI says so.
+func Disconnect(opts DisconnectOptions) error {
+ manager := opts.Forwarder
+ if manager == nil {
+ manager = service.ForwarderManager{UserMode: opts.UserMode}
+ }
+ var problems []error
+ if err := manager.Unload(); err != nil {
+ problems = append(problems, fmt.Errorf("stop forwarder: %w", err))
+ }
+ manager.RemoveUnits()
+ if err := RemoveState(opts.UserMode, opts.KeepCredentials); err != nil {
+ problems = append(problems, fmt.Errorf("remove %s: %w", Dir(opts.UserMode), err))
+ }
+ if err := updateConfig(opts.UserMode, opts.LogPath, nil); err != nil && !os.IsNotExist(err) {
+ problems = append(problems, fmt.Errorf("update endpoint config: %w", err))
+ }
+ return errors.Join(problems...)
+}
+
+// updateConfig records (or clears) the non-secret managed_ingest block in config.json. A
+// missing config is created with defaults so a hook-only install can still connect.
+func updateConfig(userMode bool, logPath string, managed *endpointconfig.ManagedIngest) error {
+ cfg, err := endpointconfig.Load(userMode)
+ if err != nil {
+ if managed == nil {
+ // Clearing the block from a missing or unreadable config is nothing to do;
+ // uninstall calls this right before removing the file anyway.
+ return nil
+ }
+ if !os.IsNotExist(err) {
+ return err
+ }
+ cfg = endpointconfig.Default(userMode, logPath)
+ }
+ if managed == nil {
+ if cfg.ManagedIngest == nil {
+ return nil
+ }
+ cfg.ManagedIngest = nil
+ } else {
+ cfg.ManagedIngest = managed
+ }
+ _, err = endpointconfig.Save(cfg)
+ return err
+}
+
+func installMode(userMode bool) string {
+ if userMode {
+ return "user"
+ }
+ return "system"
+}
+
+func displayOrg(r *EnrollResult) string {
+ if r.OrganizationName != "" {
+ return r.OrganizationName
+ }
+ 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
+ if _, err := randRead(buf[:]); err != nil {
+ return "", fmt.Errorf("could not generate an install id: %w", err)
+ }
+ return fmt.Sprintf("%x", buf), nil
+}
+
+// ForwarderStatus reports the service state of the forwarder for the selected mode.
+func ForwarderStatus(userMode bool) service.Status {
+ return service.ForwarderManager{UserMode: userMode}.Status()
+}
+
+// BufferBytes is the size of Vector's on-disk buffer and checkpoints.
+func BufferBytes(userMode bool) int64 {
+ return dirSize(filepath.Join(DataDir(userMode)))
+}
diff --git a/cli/beacon/internal/endpoint/asymptote/connect_test.go b/cli/beacon/internal/endpoint/asymptote/connect_test.go
new file mode 100644
index 00000000..e6141dd6
--- /dev/null
+++ b/cli/beacon/internal/endpoint/asymptote/connect_test.go
@@ -0,0 +1,339 @@
+package asymptote
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "runtime"
+ "strconv"
+ "strings"
+ "testing"
+ "time"
+
+ endpointconfig "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/config"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/service"
+)
+
+type fakeForwarder struct {
+ supported bool
+ written []string
+ loads int
+ unloads int
+ removed int
+ loadErr error
+}
+
+func (f *fakeForwarder) Supported() bool { return f.supported }
+func (f *fakeForwarder) UnsupportedReason() string { return "fake forwarder unsupported" }
+func (f *fakeForwarder) Label() string { return "fake.forwarder" }
+func (f *fakeForwarder) WriteUnit(vectorBin, configPath string) (string, error) {
+ f.written = append(f.written, vectorBin+" --config "+configPath)
+ return "/tmp/fake.unit", nil
+}
+func (f *fakeForwarder) Load() error { f.loads++; return f.loadErr }
+func (f *fakeForwarder) Unload() error { f.unloads++; return nil }
+func (f *fakeForwarder) RemoveUnits() { f.removed++ }
+func (f *fakeForwarder) Status() service.Status {
+ return service.Status{Label: "fake.forwarder", Loaded: f.loads > 0, Running: f.loads > 0}
+}
+
+// fakeVector writes an executable that answers --version and validate like Vector 0.56.
+func fakeVector(t *testing.T, version string, validateExit int) string {
+ t.Helper()
+ if runtime.GOOS == "windows" {
+ t.Skip("fake vector script needs a POSIX shell")
+ }
+ dir := t.TempDir()
+ path := filepath.Join(dir, "vector")
+ script := "#!/bin/sh\ncase \"$1\" in\n --version) echo \"vector " + version + " (aarch64-apple-darwin test)\";;\n validate) exit " + itoa(validateExit) + ";;\n *) exit 0;;\nesac\n"
+ if err := os.WriteFile(path, []byte(script), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ return path
+}
+
+func itoa(n int) string { return strconv.Itoa(n) }
+
+func connectOptions(t *testing.T, fd *fakeDashboard, fwd *fakeForwarder, vector string) ConnectOptions {
+ t.Helper()
+ return ConnectOptions{
+ UserMode: true,
+ LogPath: filepath.Join(t.TempDir(), "runtime.jsonl"),
+ VectorBin: vector,
+ Forwarder: fwd,
+ Enroll: EnrollOptions{
+ DashboardURL: fd.server.URL,
+ Device: DeviceInfo{Hostname: "mac.local", OS: "darwin", Arch: "arm64", BeaconVersion: "test"},
+ OpenBrowser: fd.approve(t),
+ HTTPClient: fd.server.Client(),
+ Timeout: 5 * time.Second,
+ },
+ Now: func() time.Time { return time.Date(2026, 9, 4, 1, 0, 0, 0, time.UTC) },
+ }
+}
+
+func TestConnectWritesSecretsConfigUnitAndEnrollmentInOrder(t *testing.T) {
+ home := t.TempDir()
+ t.Setenv("HOME", home)
+ isolateVectorDiscovery(t)
+ fd := newFakeDashboard(t)
+ fwd := &fakeForwarder{supported: true}
+ vector := fakeVector(t, "0.56.0", 0)
+
+ result, err := Connect(context.Background(), connectOptions(t, fd, fwd, vector))
+ if err != nil {
+ t.Fatalf("Connect returned error: %v", err)
+ }
+
+ dir := Dir(true)
+ if info, err := os.Stat(dir); err != nil || info.Mode().Perm() != 0o700 {
+ t.Fatalf("asymptote dir mode: %v %v", info, err)
+ }
+ for name, mode := range map[string]os.FileMode{SecretsFileName: 0o600, EnrollmentFileName: 0o600, VectorConfigName: 0o644} {
+ info, err := os.Stat(filepath.Join(dir, name))
+ if err != nil {
+ t.Fatalf("%s: %v", name, err)
+ }
+ if info.Mode().Perm() != mode {
+ t.Fatalf("%s mode = %o, want %o", name, info.Mode().Perm(), mode)
+ }
+ }
+ if info, err := os.Stat(DataDir(true)); err != nil || !info.IsDir() || info.Mode().Perm() != 0o700 {
+ t.Fatalf("data dir: %v %v", info, err)
+ }
+
+ key, err := ReadDeviceKey(true)
+ if err != nil || !strings.HasPrefix(key, "bcn_device_abcdefgh_") {
+ t.Fatalf("stored key = %q (%v)", key, err)
+ }
+ toml, _ := os.ReadFile(VectorConfigPath(true))
+ if strings.Contains(string(toml), "bcn_device") || strings.Contains(string(toml), "${") {
+ t.Fatalf("vector.toml must hold neither the key nor env references:\n%s", toml)
+ }
+ for _, want := range []string{
+ `uri = "https://ingest.example.test/v1/ingest/runtime"`,
+ `path = "` + SecretsPath(true) + `"`,
+ `data_dir = "` + DataDir(true) + `"`,
+ } {
+ if !strings.Contains(string(toml), want) {
+ t.Fatalf("vector.toml missing %q:\n%s", want, toml)
+ }
+ }
+ if len(fwd.written) != 1 || !strings.HasPrefix(fwd.written[0], vector+" --config "+VectorConfigPath(true)) || fwd.loads != 1 {
+ t.Fatalf("forwarder calls = %v loads=%d", fwd.written, fwd.loads)
+ }
+
+ enrollment, err := LoadEnrollment(true)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if enrollment.DeviceID != "dev-1" || enrollment.OrganizationName != "Asymptote Test" || enrollment.InstallID == "" || enrollment.VectorVersion != "0.56.0" {
+ t.Fatalf("enrollment = %+v", enrollment)
+ }
+ if result.ReEnrolled || result.Enrollment.DeviceID != "dev-1" || result.SecretsFile != SecretsPath(true) {
+ t.Fatalf("result = %+v", result)
+ }
+ cfg, err := endpointconfig.Load(true)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if cfg.ManagedIngest == nil || !cfg.ManagedIngest.Enabled || cfg.ManagedIngest.DeviceID != "dev-1" || cfg.ManagedIngest.IngestURL != "https://ingest.example.test" {
+ t.Fatalf("config managed_ingest = %+v", cfg.ManagedIngest)
+ }
+ raw, _ := os.ReadFile(endpointconfig.ConfigPath(true))
+ if strings.Contains(string(raw), "bcn_device") {
+ t.Fatalf("config.json must never contain the device key: %s", raw)
+ }
+ if endpointconfig.HasSecretDestinations(cfg) {
+ t.Fatal("managed ingest must not count as a secret destination in config.json")
+ }
+}
+
+func TestConnectReusesInstallIDOnReEnrollment(t *testing.T) {
+ home := t.TempDir()
+ t.Setenv("HOME", home)
+ isolateVectorDiscovery(t)
+ fd := newFakeDashboard(t)
+ fwd := &fakeForwarder{supported: true}
+ vector := fakeVector(t, "0.57.1", 0)
+
+ if _, err := Connect(context.Background(), connectOptions(t, fd, fwd, vector)); err != nil {
+ t.Fatal(err)
+ }
+ first, _ := LoadEnrollment(true)
+ result, err := Connect(context.Background(), connectOptions(t, fd, fwd, vector))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !result.ReEnrolled || result.Enrollment.InstallID != first.InstallID {
+ t.Fatalf("re-enrollment should reuse install id %s: %+v", first.InstallID, result)
+ }
+ fd.mu.Lock()
+ defer fd.mu.Unlock()
+ if fd.init["device"].(map[string]any)["install_id"] != first.InstallID {
+ t.Fatalf("second init sent install_id %v", fd.init["device"])
+ }
+ if fwd.loads != 2 {
+ t.Fatalf("forwarder should be (re)loaded on each connect, loads=%d", fwd.loads)
+ }
+}
+
+func TestConnectStopsBeforeTheBrowserWhenVectorIsMissingOrOld(t *testing.T) {
+ home := t.TempDir()
+ t.Setenv("HOME", home)
+ isolateVectorDiscovery(t)
+ fd := newFakeDashboard(t)
+ fwd := &fakeForwarder{supported: true}
+ opened := false
+ opts := connectOptions(t, fd, fwd, filepath.Join(t.TempDir(), "missing-vector"))
+ opts.Enroll.OpenBrowser = func(string) error { opened = true; return nil }
+
+ if _, err := Connect(context.Background(), opts); err == nil || (!errors.Is(err, ErrVectorNotFound) && !strings.Contains(err.Error(), "vector")) {
+ t.Fatalf("expected a Vector error, got %v", err)
+ }
+ opts = connectOptions(t, fd, fwd, fakeVector(t, "0.55.9", 0))
+ opts.Enroll.OpenBrowser = func(string) error { opened = true; return nil }
+ if _, err := Connect(context.Background(), opts); err == nil || !strings.Contains(err.Error(), "0.56.0 or newer") {
+ t.Fatalf("expected a too-old error, got %v", err)
+ }
+ if opened {
+ t.Fatal("browser must not open when Vector is unusable")
+ }
+ if _, err := os.Stat(SecretsPath(true)); !os.IsNotExist(err) {
+ t.Fatal("no secrets file may exist after a failed connect")
+ }
+}
+
+func TestConnectRefusesUnsupportedServiceManagerBeforeEnrolling(t *testing.T) {
+ home := t.TempDir()
+ t.Setenv("HOME", home)
+ fd := newFakeDashboard(t)
+ opened := false
+ opts := connectOptions(t, fd, &fakeForwarder{supported: false}, fakeVector(t, "0.56.0", 0))
+ opts.Enroll.OpenBrowser = func(string) error { opened = true; return nil }
+ if _, err := Connect(context.Background(), opts); err == nil || !strings.Contains(err.Error(), "fake forwarder unsupported") {
+ t.Fatalf("expected unsupported error, got %v", err)
+ }
+ if opened {
+ t.Fatal("browser must not open when no service manager is available")
+ }
+}
+
+func TestConnectFailsWhenVectorValidateRejectsTheConfig(t *testing.T) {
+ home := t.TempDir()
+ t.Setenv("HOME", home)
+ fd := newFakeDashboard(t)
+ fwd := &fakeForwarder{supported: true}
+ if _, err := Connect(context.Background(), connectOptions(t, fd, fwd, fakeVector(t, "0.56.0", 78))); err == nil || !strings.Contains(err.Error(), "vector validate failed") {
+ t.Fatalf("expected validate failure, got %v", err)
+ }
+ if len(fwd.written) != 0 || fwd.loads != 0 {
+ t.Fatal("no unit may be written or loaded when validation fails")
+ }
+ if _, err := LoadEnrollment(true); !errors.Is(err, ErrNotEnrolled) {
+ t.Fatalf("enrollment must not be recorded after a failed connect, got %v", err)
+ }
+}
+
+func TestDisconnectRemovesForwarderAndOptionallyKeepsCredentials(t *testing.T) {
+ home := t.TempDir()
+ t.Setenv("HOME", home)
+ fd := newFakeDashboard(t)
+ fwd := &fakeForwarder{supported: true}
+ if _, err := Connect(context.Background(), connectOptions(t, fd, fwd, fakeVector(t, "0.56.0", 0))); err != nil {
+ t.Fatal(err)
+ }
+
+ if err := Disconnect(DisconnectOptions{UserMode: true, Forwarder: fwd, KeepCredentials: true}); err != nil {
+ t.Fatal(err)
+ }
+ if fwd.unloads != 1 || fwd.removed != 1 {
+ t.Fatalf("forwarder unloads=%d removed=%d", fwd.unloads, fwd.removed)
+ }
+ if _, err := os.Stat(VectorConfigPath(true)); !os.IsNotExist(err) {
+ t.Fatal("vector.toml should be removed")
+ }
+ if _, err := os.Stat(DataDir(true)); !os.IsNotExist(err) {
+ t.Fatal("data dir should be removed")
+ }
+ if _, err := LoadEnrollment(true); err != nil {
+ t.Fatalf("enrollment should be kept: %v", err)
+ }
+ if _, err := ReadDeviceKey(true); err != nil {
+ t.Fatalf("device key should be kept: %v", err)
+ }
+ cfg, _ := endpointconfig.Load(true)
+ if cfg.ManagedIngest != nil {
+ t.Fatalf("config managed_ingest should be cleared, got %+v", cfg.ManagedIngest)
+ }
+
+ if err := Disconnect(DisconnectOptions{UserMode: true, Forwarder: fwd}); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := os.Stat(Dir(true)); !os.IsNotExist(err) {
+ t.Fatal("asymptote dir should be removed entirely")
+ }
+ // Disconnecting an endpoint that was never connected is not an error.
+ if err := Disconnect(DisconnectOptions{UserMode: true, Forwarder: fwd}); err != nil {
+ t.Fatalf("second disconnect should be a no-op, got %v", err)
+ }
+}
+
+func TestStatusReportsCredentialState(t *testing.T) {
+ home := t.TempDir()
+ t.Setenv("HOME", home)
+ if got := Status(true, StatusOptions{}); got.Enabled || got.Message != "" {
+ t.Fatalf("not enrolled status = %+v", got)
+ }
+
+ var answer int
+ ingest := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != CredentialCheckPath || !strings.HasPrefix(r.Header.Get("Authorization"), "Bearer bcn_device_") {
+ w.WriteHeader(http.StatusBadRequest)
+ return
+ }
+ w.WriteHeader(answer)
+ }))
+ defer ingest.Close()
+ if err := SaveEnrollment(true, Enrollment{InstallID: "i", IngestURL: ingest.URL, DeviceID: "dev-1", KeyPrefix: "bcn_device_abcdefgh", OrganizationName: "Asymptote Test", EnrolledAt: time.Now()}); err != nil {
+ t.Fatal(err)
+ }
+ if err := WriteSecrets(true, "bcn_device_abcdefgh_"+strings.Repeat("k", 43)); 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()})
+ if !got.Enabled || got.Credential != want || got.DeviceID != "dev-1" {
+ t.Fatalf("status for %d = %+v, want credential %q", status, got, want)
+ }
+ }
+ ingest.Close()
+ got := Status(true, StatusOptions{HTTPClient: &http.Client{Timeout: 500 * time.Millisecond}})
+ if got.Credential != "unknown" || !strings.Contains(got.CredentialMessage, "unreachable") {
+ t.Fatalf("offline status = %+v", got)
+ }
+ if skipped := Status(true, StatusOptions{SkipCredentialCheck: true}); skipped.Credential != "" || !skipped.Enabled {
+ t.Fatalf("skip should not touch the network: %+v", skipped)
+ }
+ var encoded map[string]any
+ if err := json.Unmarshal(mustJSON(t, got), &encoded); err != nil {
+ t.Fatal(err)
+ }
+ if _, ok := encoded["device_key"]; ok {
+ t.Fatal("status JSON must never include the device key")
+ }
+}
+
+func mustJSON(t *testing.T, v any) []byte {
+ t.Helper()
+ data, err := json.Marshal(v)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return data
+}
diff --git a/cli/beacon/internal/endpoint/asymptote/enroll.go b/cli/beacon/internal/endpoint/asymptote/enroll.go
new file mode 100644
index 00000000..8c8f1c57
--- /dev/null
+++ b/cli/beacon/internal/endpoint/asymptote/enroll.go
@@ -0,0 +1,205 @@
+package asymptote
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "net/url"
+ "strings"
+ "time"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/auth"
+)
+
+// Dashboard paths for device enrollment. The page and the two API routes are served by the
+// Asymptote dashboard, which proxies to the platform API.
+const (
+ EnrollPagePath = "/cli/enroll"
+ EnrollInitPath = "/api/cli/enroll/init"
+ EnrollExchangePath = "/api/cli/enroll/exchange"
+)
+
+// DeviceInfo is what the CLI tells the dashboard about this machine. It is shown on the
+// approval page and stored on the device record; none of it is secret.
+type DeviceInfo struct {
+ InstallID string `json:"install_id"`
+ Hostname string `json:"hostname"`
+ OS string `json:"os"`
+ Arch string `json:"arch"`
+ BeaconVersion string `json:"beacon_version"`
+ InstallMode string `json:"install_mode"`
+}
+
+// EnrollOptions configures one enrollment round trip.
+type EnrollOptions struct {
+ DashboardURL string
+ Device DeviceInfo
+ // OpenBrowser opens the approval page; nil uses the platform default. Callers running as
+ // root pass one that opens the browser as the console user.
+ OpenBrowser func(string) error
+ // NoBrowser prints the URL instead of opening anything.
+ NoBrowser bool
+ HTTPClient *http.Client
+ Out io.Writer
+ Timeout time.Duration
+}
+
+// EnrollResult is the exchange response. DeviceKey is shown to nobody and written only to
+// the secrets file.
+type EnrollResult struct {
+ DeviceID string `json:"device_id"`
+ DeviceKey string `json:"device_key"`
+ KeyPrefix string `json:"key_prefix"`
+ IngestURL string `json:"ingest_url"`
+ OrganizationID string `json:"organization_id"`
+ OrganizationName string `json:"organization_name"`
+ Email string `json:"email"`
+ Scopes []string `json:"scopes"`
+ ExpiresAt *string `json:"expires_at"`
+}
+
+type enrollInitRequest struct {
+ CodeChallenge string `json:"code_challenge"`
+ CodeChallengeMethod string `json:"code_challenge_method"`
+ State string `json:"state"`
+ RedirectPort int `json:"redirect_port"`
+ Device DeviceInfo `json:"device"`
+}
+
+type enrollExchangeRequest struct {
+ ExchangeCode string `json:"exchange_code"`
+ State string `json:"state"`
+ CodeVerifier string `json:"code_verifier"`
+}
+
+// Enroll runs the browser approval flow and returns the minted device key.
+//
+// Order matters for safety: the session is registered with the dashboard first (so the
+// approval page can show the device details), the browser is opened to a URL that carries
+// only the state and the loopback port, and the key is minted only when the callback's
+// 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) {
+ return nil, fmt.Errorf("dashboard URL must use https://: %s", dashboardURL)
+ }
+ if opts.Device.InstallID == "" {
+ return nil, errors.New("enrollment needs an install id")
+ }
+ timeout := opts.Timeout
+ if timeout == 0 {
+ timeout = auth.AuthTimeout
+ }
+ client := opts.HTTPClient
+ if client == nil {
+ client = &http.Client{Timeout: 30 * time.Second}
+ }
+ out := opts.Out
+ if out == nil {
+ out = io.Discard
+ }
+ openBrowser := opts.OpenBrowser
+ if openBrowser == nil {
+ openBrowser = auth.OpenBrowser
+ }
+
+ pkce, err := auth.GeneratePKCE()
+ if err != nil {
+ return nil, fmt.Errorf("failed to generate PKCE parameters: %w", err)
+ }
+
+ var result *EnrollResult
+ exchange := func(ctx context.Context, exchangeCode, state, codeVerifier string) error {
+ var resp EnrollResult
+ if err := auth.PostJSON(ctx, client, dashboardURL+EnrollExchangePath, enrollExchangeRequest{
+ ExchangeCode: exchangeCode,
+ State: state,
+ CodeVerifier: codeVerifier,
+ }, &resp); err != nil {
+ return err
+ }
+ if err := validateEnrollResult(&resp); err != nil {
+ return err
+ }
+ result = &resp
+ return nil
+ }
+ server, err := auth.NewCallbackServer(pkce.State, pkce.CodeVerifier, exchange, client.Timeout)
+ if err != nil {
+ return nil, err
+ }
+ server.SetSuccessPage("Beacon: device connected", "This machine is now forwarding to Asymptote. You can close this tab and return to the terminal.")
+ defer func() { _ = server.Shutdown() }()
+ server.Start()
+
+ if err := auth.PostJSON(ctx, client, dashboardURL+EnrollInitPath, enrollInitRequest{
+ CodeChallenge: pkce.CodeChallenge,
+ CodeChallengeMethod: "S256",
+ State: pkce.State,
+ RedirectPort: server.Port(),
+ Device: opts.Device,
+ }, nil); err != nil {
+ return nil, fmt.Errorf("could not start enrollment with %s: %w", dashboardURL, err)
+ }
+
+ approvalURL := buildEnrollURL(dashboardURL, pkce.State, server.Port())
+ if opts.NoBrowser {
+ fmt.Fprintf(out, "Open this URL in a browser where you are signed in to Asymptote:\n%s\n", approvalURL)
+ } else {
+ fmt.Fprintf(out, "Opening %s%s in your browser...\n", dashboardURL, EnrollPagePath)
+ if err := openBrowser(approvalURL); err != nil {
+ fmt.Fprintln(out, "Could not open a browser automatically.")
+ fmt.Fprintf(out, "Open this URL in a browser where you are signed in to Asymptote:\n%s\n", approvalURL)
+ }
+ }
+ fmt.Fprintln(out, "Waiting for a member of your organization to approve this device...")
+
+ callback, err := server.Wait(timeout)
+ if err != nil {
+ return nil, err
+ }
+ if callback.Error != "" {
+ return nil, fmt.Errorf("enrollment failed: %s", callback.Error)
+ }
+ if result == nil {
+ return nil, errors.New("enrollment finished without a device key")
+ }
+ return result, nil
+}
+
+func validateEnrollResult(r *EnrollResult) error {
+ switch {
+ case r.DeviceKey == "" || !strings.HasPrefix(r.DeviceKey, "bcn_device_"):
+ 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):
+ return fmt.Errorf("exchange response ingest URL must use https://: %q", r.IngestURL)
+ }
+ r.IngestURL = strings.TrimRight(r.IngestURL, "/")
+ return nil
+}
+
+func buildEnrollURL(dashboardURL, state string, port int) string {
+ u, err := url.Parse(dashboardURL + EnrollPagePath)
+ if err != nil {
+ return dashboardURL + EnrollPagePath
+ }
+ q := u.Query()
+ q.Set("state", state)
+ q.Set("port", fmt.Sprintf("%d", port))
+ u.RawQuery = q.Encode()
+ 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 {
+ return false
+ }
+ host := u.Hostname()
+ return host == "127.0.0.1" || host == "localhost" || host == "::1"
+}
diff --git a/cli/beacon/internal/endpoint/asymptote/enroll_test.go b/cli/beacon/internal/endpoint/asymptote/enroll_test.go
new file mode 100644
index 00000000..f46fd91f
--- /dev/null
+++ b/cli/beacon/internal/endpoint/asymptote/enroll_test.go
@@ -0,0 +1,262 @@
+package asymptote
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+)
+
+// fakeDashboard stands in for asymptotelabs.ai: it records the init request, and when the
+// "browser" is opened it plays the approving user by redirecting to the CLI's callback with a
+// one-time code, then validates the PKCE exchange.
+type fakeDashboard struct {
+ mu sync.Mutex
+ init map[string]any
+ exchange map[string]any
+ exchangeCode string
+ ingestURL string
+ server *httptest.Server
+ initStatus int
+ exchangeFail string
+}
+
+func newFakeDashboard(t *testing.T) *fakeDashboard {
+ t.Helper()
+ fd := &fakeDashboard{exchangeCode: "code-123", initStatus: http.StatusCreated}
+ fd.server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ body, _ := io.ReadAll(r.Body)
+ var payload map[string]any
+ _ = json.Unmarshal(body, &payload)
+ fd.mu.Lock()
+ defer fd.mu.Unlock()
+ switch r.URL.Path {
+ case EnrollInitPath:
+ fd.init = payload
+ w.WriteHeader(fd.initStatus)
+ if fd.initStatus >= 400 {
+ _, _ = w.Write([]byte(`{"detail":"too many enrollment attempts"}`))
+ return
+ }
+ _, _ = w.Write([]byte(`{"session_id":"s1","state":"` + payload["state"].(string) + `","expires_at":"2026-09-04T00:00:00Z"}`))
+ case EnrollExchangePath:
+ fd.exchange = payload
+ if fd.exchangeFail != "" {
+ w.WriteHeader(http.StatusGone)
+ _, _ = w.Write([]byte(`{"detail":"` + fd.exchangeFail + `"}`))
+ return
+ }
+ if payload["exchange_code"] != fd.exchangeCode {
+ w.WriteHeader(http.StatusBadRequest)
+ _, _ = w.Write([]byte(`{"detail":"bad code"}`))
+ return
+ }
+ ingest := fd.ingestURL
+ if ingest == "" {
+ ingest = "https://ingest.example.test"
+ }
+ _ = json.NewEncoder(w).Encode(map[string]any{
+ "device_id": "dev-1",
+ "device_key": "bcn_device_abcdefgh_" + strings.Repeat("k", 43),
+ "key_prefix": "bcn_device_abcdefgh",
+ "ingest_url": ingest,
+ "organization_id": "org-1",
+ "organization_name": "Asymptote Test",
+ "email": "[email protected]",
+ "scopes": []string{"ingest:write"},
+ })
+ default:
+ w.WriteHeader(http.StatusNotFound)
+ }
+ }))
+ t.Cleanup(fd.server.Close)
+ return fd
+}
+
+// approve simulates the user clicking Approve: the dashboard redirects the browser to the
+// CLI's callback with the exchange code and state taken from the approval URL.
+func (fd *fakeDashboard) approve(t *testing.T) func(string) error {
+ return func(approvalURL string) error {
+ u, err := url.Parse(approvalURL)
+ if err != nil {
+ return err
+ }
+ if u.Path != EnrollPagePath {
+ t.Errorf("browser opened %s, want %s", u.Path, EnrollPagePath)
+ }
+ if u.Query().Get("code_challenge") != "" {
+ t.Errorf("approval URL must not carry the code challenge: %s", approvalURL)
+ }
+ state, port := u.Query().Get("state"), u.Query().Get("port")
+ go func() {
+ resp, err := http.Get(fmt.Sprintf("http://127.0.0.1:%s/callback?state=%s&exchange_code=%s", port, state, fd.exchangeCode))
+ if err == nil {
+ resp.Body.Close()
+ }
+ }()
+ return nil
+ }
+}
+
+func device() DeviceInfo {
+ return DeviceInfo{InstallID: "install-1", Hostname: "mac.local", OS: "darwin", Arch: "arm64", BeaconVersion: "test", InstallMode: "user"}
+}
+
+func TestEnrollRegistersDeviceOpensBrowserAndExchangesWithPKCE(t *testing.T) {
+ fd := newFakeDashboard(t)
+ var out strings.Builder
+ result, err := Enroll(context.Background(), EnrollOptions{
+ DashboardURL: fd.server.URL,
+ Device: device(),
+ OpenBrowser: fd.approve(t),
+ HTTPClient: fd.server.Client(),
+ Out: &out,
+ Timeout: 5 * time.Second,
+ })
+ if err != nil {
+ t.Fatalf("Enroll returned error: %v", err)
+ }
+ if result.DeviceID != "dev-1" || !strings.HasPrefix(result.DeviceKey, "bcn_device_abcdefgh_") || result.IngestURL != "https://ingest.example.test" {
+ t.Fatalf("unexpected result %+v", result)
+ }
+ fd.mu.Lock()
+ defer fd.mu.Unlock()
+ if fd.init["code_challenge_method"] != "S256" || fd.init["state"] == "" || fd.init["redirect_port"] == nil {
+ t.Fatalf("init payload = %v", fd.init)
+ }
+ dev := fd.init["device"].(map[string]any)
+ if dev["install_id"] != "install-1" || dev["hostname"] != "mac.local" || dev["install_mode"] != "user" {
+ t.Fatalf("device payload = %v", dev)
+ }
+ if fd.exchange["state"] != fd.init["state"] || fd.exchange["code_verifier"] == "" || fd.exchange["exchange_code"] != "code-123" {
+ t.Fatalf("exchange payload = %v", fd.exchange)
+ }
+ if !strings.Contains(out.String(), "Waiting for a member of your organization") {
+ t.Fatalf("output = %q", out.String())
+ }
+}
+
+func TestEnrollSurfacesInitRejectionWithoutOpeningABrowser(t *testing.T) {
+ fd := newFakeDashboard(t)
+ fd.initStatus = http.StatusTooManyRequests
+ opened := false
+ _, err := Enroll(context.Background(), EnrollOptions{
+ DashboardURL: fd.server.URL,
+ Device: device(),
+ OpenBrowser: func(string) error { opened = true; return nil },
+ HTTPClient: fd.server.Client(),
+ Timeout: 2 * time.Second,
+ })
+ if err == nil || !strings.Contains(err.Error(), "too many enrollment attempts") {
+ t.Fatalf("expected the server detail, got %v", err)
+ }
+ if opened {
+ t.Fatal("browser must not open when init fails")
+ }
+}
+
+func TestEnrollReportsExchangeFailure(t *testing.T) {
+ fd := newFakeDashboard(t)
+ fd.exchangeFail = "exchange code has expired; restart enrollment"
+ _, err := Enroll(context.Background(), EnrollOptions{
+ DashboardURL: fd.server.URL,
+ Device: device(),
+ OpenBrowser: fd.approve(t),
+ HTTPClient: fd.server.Client(),
+ Timeout: 5 * time.Second,
+ })
+ if err == nil || !strings.Contains(err.Error(), "exchange code has expired") {
+ t.Fatalf("expected exchange failure, got %v", err)
+ }
+}
+
+func TestEnrollRefusesInsecureIngestURLFromServer(t *testing.T) {
+ fd := newFakeDashboard(t)
+ fd.ingestURL = "http://ingest.example.test"
+ _, err := Enroll(context.Background(), EnrollOptions{
+ DashboardURL: fd.server.URL,
+ Device: device(),
+ OpenBrowser: fd.approve(t),
+ HTTPClient: fd.server.Client(),
+ Timeout: 5 * time.Second,
+ })
+ if err == nil || !strings.Contains(err.Error(), "https://") {
+ t.Fatalf("expected https enforcement, got %v", err)
+ }
+}
+
+func TestEnrollRefusesInsecureDashboardAndMissingInstallID(t *testing.T) {
+ if _, err := Enroll(context.Background(), EnrollOptions{DashboardURL: "http://dash.example.test", Device: device()}); err == nil {
+ t.Fatal("expected error for http dashboard URL")
+ }
+ fd := newFakeDashboard(t)
+ d := device()
+ d.InstallID = ""
+ if _, err := Enroll(context.Background(), EnrollOptions{DashboardURL: fd.server.URL, Device: d, HTTPClient: fd.server.Client()}); err == nil {
+ t.Fatal("expected error for missing install id")
+ }
+}
+
+// syncBuffer is an io.Writer safe to read from another goroutine.
+type syncBuffer struct {
+ mu sync.Mutex
+ b strings.Builder
+}
+
+func (s *syncBuffer) Write(p []byte) (int, error) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return s.b.Write(p)
+}
+
+func (s *syncBuffer) String() string {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return s.b.String()
+}
+
+func TestEnrollNoBrowserPrintsTheURL(t *testing.T) {
+ fd := newFakeDashboard(t)
+ var out syncBuffer
+ approve := fd.approve(t)
+ // NoBrowser prints the URL; the test approves from the printed text.
+ done := make(chan struct{})
+ go func() {
+ defer close(done)
+ for i := 0; i < 100; i++ {
+ text := out.String()
+ if idx := strings.Index(text, "http://"); idx >= 0 {
+ line := text[idx:]
+ if nl := strings.IndexByte(line, '\n'); nl >= 0 {
+ line = line[:nl]
+ }
+ _ = approve(line)
+ return
+ }
+ time.Sleep(20 * time.Millisecond)
+ }
+ }()
+ _, err := Enroll(context.Background(), EnrollOptions{
+ DashboardURL: fd.server.URL,
+ Device: device(),
+ NoBrowser: true,
+ OpenBrowser: func(string) error { t.Error("browser must not open with NoBrowser"); return nil },
+ HTTPClient: fd.server.Client(),
+ Out: &out,
+ Timeout: 5 * time.Second,
+ })
+ <-done
+ if err != nil {
+ t.Fatalf("Enroll returned error: %v", err)
+ }
+ if !strings.Contains(out.String(), "Open this URL in a browser") {
+ t.Fatalf("output = %q", out.String())
+ }
+}
diff --git a/cli/beacon/internal/endpoint/asymptote/enrollment.go b/cli/beacon/internal/endpoint/asymptote/enrollment.go
new file mode 100644
index 00000000..8bb8b160
--- /dev/null
+++ b/cli/beacon/internal/endpoint/asymptote/enrollment.go
@@ -0,0 +1,170 @@
+package asymptote
+
+import (
+ "encoding/json"
+ "errors"
+ "fmt"
+ "os"
+ "path/filepath"
+ "strings"
+ "time"
+
+ endpointconfig "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/config"
+)
+
+// Files under <BaseDir>/asymptote/. The directory is 0700 and the two credential-adjacent
+// files are 0600; vector.toml is 0644 because it holds no secret, only the SECRET[] reference.
+const (
+ DirName = "asymptote"
+ EnrollmentFileName = "enrollment.json"
+ SecretsFileName = "vector-secrets.json"
+ VectorConfigName = "vector.toml"
+ DataDirName = "vector-data"
+)
+
+// Dir is the managed-ingest state directory for the selected endpoint mode.
+func Dir(userMode bool) string { return filepath.Join(endpointconfig.BaseDir(userMode), DirName) }
+
+// EnrollmentPath, SecretsPath, VectorConfigPath and DataDir locate the individual files.
+func EnrollmentPath(userMode bool) string { return filepath.Join(Dir(userMode), EnrollmentFileName) }
+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) }
+
+// 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.
+type Enrollment struct {
+ InstallID string `json:"install_id"`
+ IngestURL string `json:"ingest_url"`
+ DashboardURL string `json:"dashboard_url"`
+ DeviceID string `json:"device_id"`
+ KeyPrefix string `json:"key_prefix"`
+ OrganizationID string `json:"organization_id"`
+ OrganizationName string `json:"organization_name,omitempty"`
+ Email string `json:"email,omitempty"`
+ EnrolledAt time.Time `json:"enrolled_at"`
+ ExpiresAt string `json:"expires_at,omitempty"`
+ VectorBin string `json:"vector_bin,omitempty"`
+ VectorVersion string `json:"vector_version,omitempty"`
+}
+
+// ErrNotEnrolled is returned when no enrollment record exists.
+var ErrNotEnrolled = errors.New("this endpoint is not connected to Asymptote managed ingest")
+
+// LoadEnrollment reads the enrollment record.
+func LoadEnrollment(userMode bool) (*Enrollment, error) {
+ data, err := os.ReadFile(EnrollmentPath(userMode))
+ if err != nil {
+ if os.IsNotExist(err) {
+ return nil, ErrNotEnrolled
+ }
+ return nil, err
+ }
+ var enrollment Enrollment
+ if err := json.Unmarshal(data, &enrollment); err != nil {
+ return nil, fmt.Errorf("enrollment record %s is not valid JSON: %w", EnrollmentPath(userMode), err)
+ }
+ return &enrollment, nil
+}
+
+// SaveEnrollment writes the record with 0600 permissions inside a 0700 directory.
+func SaveEnrollment(userMode bool, enrollment Enrollment) error {
+ if err := ensureDir(userMode); err != nil {
+ return err
+ }
+ data, err := json.MarshalIndent(enrollment, "", " ")
+ if err != nil {
+ return err
+ }
+ return writeFileAtomic(EnrollmentPath(userMode), append(data, '\n'), 0o600)
+}
+
+// WriteSecrets stores the device key in the file Vector's secret backend reads.
+func WriteSecrets(userMode bool, deviceKey string) error {
+ if !strings.HasPrefix(deviceKey, "bcn_device_") {
+ return errors.New("refusing to store a credential that is not a Beacon device key")
+ }
+ if err := ensureDir(userMode); err != nil {
+ return err
+ }
+ return writeFileAtomic(SecretsPath(userMode), []byte(SecretsFileContent(deviceKey)), 0o600)
+}
+
+// ReadDeviceKey returns the stored device key, for the credential check.
+func ReadDeviceKey(userMode bool) (string, error) {
+ data, err := os.ReadFile(SecretsPath(userMode))
+ if err != nil {
+ if os.IsNotExist(err) {
+ return "", ErrNotEnrolled
+ }
+ return "", err
+ }
+ var secrets map[string]string
+ if err := json.Unmarshal(data, &secrets); err != nil {
+ return "", fmt.Errorf("secrets file %s is not valid JSON: %w", SecretsPath(userMode), err)
+ }
+ key := secrets[SecretsKey]
+ if key == "" {
+ return "", fmt.Errorf("secrets file %s has no %s", SecretsPath(userMode), SecretsKey)
+ }
+ return key, nil
+}
+
+// RemoveState deletes the managed-ingest directory. With keepCredentials the enrollment record
+// and secrets file stay so a later connect can rotate in place without a new approval.
+func RemoveState(userMode bool, keepCredentials bool) error {
+ dir := Dir(userMode)
+ if !keepCredentials {
+ if err := os.RemoveAll(dir); err != nil && !os.IsNotExist(err) {
+ return err
+ }
+ return nil
+ }
+ for _, path := range []string{VectorConfigPath(userMode), DataDir(userMode)} {
+ if err := os.RemoveAll(path); err != nil && !os.IsNotExist(err) {
+ return err
+ }
+ }
+ return nil
+}
+
+func ensureDir(userMode bool) error {
+ dir := Dir(userMode)
+ if err := os.MkdirAll(dir, 0o700); err != nil {
+ return err
+ }
+ // MkdirAll leaves an existing directory's mode alone; tighten it in case it was created
+ // by an older tool or by hand.
+ return os.Chmod(dir, 0o700)
+}
+
+// writeFileAtomic writes via a temp file in the same directory so a crash never leaves a
+// half-written credential, and sets the mode before the rename so the content is never
+// readable with wider permissions.
+func writeFileAtomic(path string, data []byte, mode os.FileMode) error {
+ tmp, err := os.CreateTemp(filepath.Dir(path), "."+filepath.Base(path)+".*")
+ if err != nil {
+ return err
+ }
+ tmpName := tmp.Name()
+ cleanup := func() { _ = os.Remove(tmpName) }
+ if err := tmp.Chmod(mode); err != nil {
+ tmp.Close()
+ cleanup()
+ return err
+ }
+ if _, err := tmp.Write(data); err != nil {
+ tmp.Close()
+ cleanup()
+ return err
+ }
+ if err := tmp.Close(); err != nil {
+ cleanup()
+ return err
+ }
+ if err := os.Rename(tmpName, path); err != nil {
+ cleanup()
+ return err
+ }
+ return nil
+}
diff --git a/cli/beacon/internal/endpoint/asymptote/status.go b/cli/beacon/internal/endpoint/asymptote/status.go
new file mode 100644
index 00000000..d0beae53
--- /dev/null
+++ b/cli/beacon/internal/endpoint/asymptote/status.go
@@ -0,0 +1,110 @@
+package asymptote
+
+import (
+ "context"
+ "crypto/rand"
+ "errors"
+ "fmt"
+ "net/http"
+ "time"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/service"
+)
+
+var randRead = rand.Read
+
+// CredentialCheckTimeout bounds the network call status makes; status must stay fast offline.
+const CredentialCheckTimeout = 3 * time.Second
+
+// ManagedIngestStatus is what `beacon endpoint status` reports about managed forwarding.
+type ManagedIngestStatus struct {
+ Enabled bool `json:"enabled"`
+ IngestURL string `json:"ingest_url,omitempty"`
+ DeviceID string `json:"device_id,omitempty"`
+ KeyPrefix string `json:"key_prefix,omitempty"`
+ OrganizationID string `json:"organization_id,omitempty"`
+ OrganizationName string `json:"organization_name,omitempty"`
+ Email string `json:"email,omitempty"`
+ EnrolledAt string `json:"enrolled_at,omitempty"`
+ VectorBin string `json:"vector_bin,omitempty"`
+ Forwarder service.Status `json:"forwarder"`
+ // Credential is "valid", "revoked", "unknown" (network unavailable) or "" when not
+ // enabled. Revoked covers every 401 cause: revoked or expired key, or the approving
+ // user leaving the organization.
+ Credential string `json:"credential,omitempty"`
+ CredentialMessage string `json:"credential_message,omitempty"`
+ BufferBytes int64 `json:"buffer_bytes"`
+ Message string `json:"message,omitempty"`
+}
+
+// StatusOptions tunes Status; zero values are the production defaults.
+type StatusOptions struct {
+ HTTPClient *http.Client
+ // SkipCredentialCheck avoids the network call (tests, offline diagnostics).
+ SkipCredentialCheck bool
+}
+
+// Status describes the managed-ingest state of this endpoint. It never reads the device key
+// into the caller's structures: the key is used for one HEAD-equivalent GET and discarded.
+func Status(userMode bool, opts StatusOptions) ManagedIngestStatus {
+ enrollment, err := LoadEnrollment(userMode)
+ if err != nil {
+ status := ManagedIngestStatus{Enabled: false}
+ if !errors.Is(err, ErrNotEnrolled) {
+ status.Message = err.Error()
+ }
+ return status
+ }
+ status := ManagedIngestStatus{
+ Enabled: true,
+ IngestURL: enrollment.IngestURL,
+ DeviceID: enrollment.DeviceID,
+ KeyPrefix: enrollment.KeyPrefix,
+ OrganizationID: enrollment.OrganizationID,
+ OrganizationName: enrollment.OrganizationName,
+ Email: enrollment.Email,
+ EnrolledAt: enrollment.EnrolledAt.UTC().Format(time.RFC3339),
+ VectorBin: enrollment.VectorBin,
+ Forwarder: ForwarderStatus(userMode),
+ BufferBytes: BufferBytes(userMode),
+ }
+ if opts.SkipCredentialCheck {
+ return status
+ }
+ status.Credential, status.CredentialMessage = CheckCredential(userMode, enrollment.IngestURL, opts.HTTPClient)
+ return status
+}
+
+// CheckCredential asks the ingest service whether the stored key is still accepted.
+func CheckCredential(userMode bool, ingestURL string, client *http.Client) (state string, message string) {
+ key, err := ReadDeviceKey(userMode)
+ if err != nil {
+ return "unknown", err.Error()
+ }
+ if client == nil {
+ client = &http.Client{Timeout: CredentialCheckTimeout}
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), CredentialCheckTimeout)
+ defer cancel()
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, ingestURL+CredentialCheckPath, nil)
+ if err != nil {
+ return "unknown", err.Error()
+ }
+ req.Header.Set("Authorization", "Bearer "+key)
+ req.Header.Set("User-Agent", "beacon-cli")
+ resp, err := client.Do(req)
+ if err != nil {
+ return "unknown", fmt.Sprintf("ingest service unreachable: %v", err)
+ }
+ defer resp.Body.Close()
+ switch resp.StatusCode {
+ case http.StatusOK, http.StatusNoContent:
+ return "valid", ""
+ case http.StatusUnauthorized:
+ return "revoked", "the device key is revoked, expired, or its approver is no longer a member; run `beacon endpoint connect` to re-enroll"
+ case http.StatusForbidden:
+ return "revoked", "managed ingest is not enabled for this organization"
+ default:
+ return "unknown", fmt.Sprintf("ingest service answered HTTP %d", resp.StatusCode)
+ }
+}
diff --git a/cli/beacon/internal/endpoint/asymptote/vector.go b/cli/beacon/internal/endpoint/asymptote/vector.go
new file mode 100644
index 00000000..bdd4c9a6
--- /dev/null
+++ b/cli/beacon/internal/endpoint/asymptote/vector.go
@@ -0,0 +1,156 @@
+package asymptote
+
+import (
+ "errors"
+ "fmt"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "regexp"
+ "runtime"
+ "strconv"
+ "strings"
+)
+
+// MinVectorVersion is the oldest Vector the forwarder template is validated against; the
+// `secret` file backend and the http sink options it uses exist from here on.
+const MinVectorVersion = "0.56.0"
+
+// VectorBinEnv names an explicit Vector binary, ahead of every search location.
+const VectorBinEnv = "BEACON_VECTOR_BIN"
+
+// PackagedVectorPath is where the signed macOS package installs Vector.
+const PackagedVectorPath = "/opt/beacon/bin/vector"
+
+// VectorInfo describes the Vector binary connect will run.
+type VectorInfo struct {
+ Path string `json:"path"`
+ Version string `json:"version"`
+}
+
+// ErrVectorNotFound is returned when no usable Vector binary exists.
+var ErrVectorNotFound = errors.New("vector was not found; install it from https://vector.dev (Homebrew: brew install vector) or set " + VectorBinEnv)
+
+// runCommandOutput is swapped by tests to fake `vector --version`.
+var runCommandOutput = func(bin string, args ...string) ([]byte, error) {
+ return exec.Command(bin, args...).CombinedOutput()
+}
+
+// lookPath is swapped by tests; defaultLookPath restores it.
+var (
+ defaultLookPath = exec.LookPath
+ lookPath = defaultLookPath
+)
+
+// FindVector locates a Vector binary of at least MinVectorVersion.
+//
+// Order: the explicit argument, BEACON_VECTOR_BIN, the packaged /opt/beacon/bin/vector, the
+// Homebrew prefixes, then PATH. The first candidate that exists is checked for version; a too-old
+// binary is an error rather than a reason to keep searching, because silently running a
+// different Vector than the one the operator pointed at would be worse.
+func FindVector(explicit string) (VectorInfo, error) {
+ for _, candidate := range vectorCandidates(explicit) {
+ if candidate == "" {
+ continue
+ }
+ path := candidate
+ if !strings.Contains(candidate, string(os.PathSeparator)) {
+ resolved, err := lookPath(candidate)
+ if err != nil {
+ continue
+ }
+ path = resolved
+ } else if info, err := os.Stat(candidate); err != nil || info.IsDir() {
+ continue
+ }
+ version, err := vectorVersion(path)
+ if err != nil {
+ return VectorInfo{}, fmt.Errorf("%s: %w", path, err)
+ }
+ if compareVersions(version, MinVectorVersion) < 0 {
+ return VectorInfo{}, fmt.Errorf("%s is Vector %s; managed forwarding needs %s or newer", path, version, MinVectorVersion)
+ }
+ return VectorInfo{Path: path, Version: version}, nil
+ }
+ return VectorInfo{}, ErrVectorNotFound
+}
+
+// vectorSearchPaths lists the fixed install locations tried after the explicit and
+// environment candidates. Tests replace it so a Vector installed on the developer's machine
+// does not leak into a test that expects none.
+var vectorSearchPaths = defaultVectorSearchPaths
+
+func defaultVectorSearchPaths() []string {
+ paths := []string{PackagedVectorPath}
+ if runtime.GOOS == "darwin" {
+ paths = append(paths, "/opt/homebrew/bin/vector", "/usr/local/bin/vector")
+ }
+ return paths
+}
+
+func vectorCandidates(explicit string) []string {
+ candidates := []string{explicit, os.Getenv(VectorBinEnv)}
+ candidates = append(candidates, vectorSearchPaths()...)
+ return append(candidates, "vector")
+}
+
+var vectorVersionPattern = regexp.MustCompile(`vector\s+v?(\d+\.\d+\.\d+)`)
+
+func vectorVersion(bin string) (string, error) {
+ out, err := runCommandOutput(bin, "--version")
+ if err != nil {
+ return "", fmt.Errorf("could not run vector --version: %w", err)
+ }
+ match := vectorVersionPattern.FindStringSubmatch(string(out))
+ if match == nil {
+ return "", fmt.Errorf("could not read a version from %q", strings.TrimSpace(string(out)))
+ }
+ return match[1], nil
+}
+
+// compareVersions orders dotted numeric versions; unparsable parts compare as zero.
+func compareVersions(a, b string) int {
+ pa, pb := strings.Split(a, "."), strings.Split(b, ".")
+ for i := 0; i < len(pa) || i < len(pb); i++ {
+ var x, y int
+ if i < len(pa) {
+ x, _ = strconv.Atoi(pa[i])
+ }
+ if i < len(pb) {
+ y, _ = strconv.Atoi(pb[i])
+ }
+ if x != y {
+ if x < y {
+ return -1
+ }
+ return 1
+ }
+ }
+ return 0
+}
+
+// ValidateVectorConfig runs `vector validate --skip-healthchecks` so a broken render is caught
+// before a service unit points at it. Health checks are skipped because they need the network
+// and the freshly written key; the service's own startup healthcheck covers that.
+func ValidateVectorConfig(vectorBin, configPath string) error {
+ out, err := runCommandOutput(vectorBin, "validate", "--skip-healthchecks", configPath)
+ if err != nil {
+ return fmt.Errorf("vector validate failed for %s: %s", configPath, strings.TrimSpace(string(out)))
+ }
+ return nil
+}
+
+// dirSize sums regular files under root; used to report the disk buffer size.
+func dirSize(root string) int64 {
+ var total int64
+ _ = filepath.WalkDir(root, func(_ string, d os.DirEntry, err error) error {
+ if err != nil || d.IsDir() {
+ return nil
+ }
+ if info, err := d.Info(); err == nil {
+ total += info.Size()
+ }
+ return nil
+ })
+ return total
+}
diff --git a/cli/beacon/internal/endpoint/asymptote/vector_test.go b/cli/beacon/internal/endpoint/asymptote/vector_test.go
new file mode 100644
index 00000000..656f3a68
--- /dev/null
+++ b/cli/beacon/internal/endpoint/asymptote/vector_test.go
@@ -0,0 +1,117 @@
+package asymptote
+
+import (
+ "errors"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+// isolateVectorDiscovery hides the machine's own Vector installs from FindVector.
+func isolateVectorDiscovery(t *testing.T) {
+ t.Helper()
+ t.Setenv(VectorBinEnv, "")
+ oldSearch, oldLook := vectorSearchPaths, lookPath
+ vectorSearchPaths = func() []string { return nil }
+ lookPath = func(string) (string, error) { return "", errors.New("not found") }
+ t.Cleanup(func() { vectorSearchPaths, lookPath = oldSearch, oldLook })
+}
+
+func TestFindVectorPrefersExplicitThenEnvAndChecksVersion(t *testing.T) {
+ isolateVectorDiscovery(t)
+ explicit := fakeVector(t, "0.56.0", 0)
+ fromEnv := fakeVector(t, "0.58.2", 0)
+ t.Setenv(VectorBinEnv, fromEnv)
+
+ got, err := FindVector(explicit)
+ if err != nil || got.Path != explicit || got.Version != "0.56.0" {
+ t.Fatalf("explicit: %+v %v", got, err)
+ }
+ got, err = FindVector("")
+ if err != nil || got.Path != fromEnv || got.Version != "0.58.2" {
+ t.Fatalf("env: %+v %v", got, err)
+ }
+ t.Setenv(VectorBinEnv, "")
+ if _, err := FindVector(""); !errors.Is(err, ErrVectorNotFound) && !strings.Contains(err.Error(), "vector") {
+ t.Fatalf("expected not found without candidates, got %v", err)
+ }
+}
+
+func TestFindVectorRejectsTooOldOrUnparsableVersions(t *testing.T) {
+ old := fakeVector(t, "0.44.0", 0)
+ if _, err := FindVector(old); err == nil || !strings.Contains(err.Error(), "0.56.0 or newer") {
+ t.Fatalf("expected too-old error, got %v", err)
+ }
+ dir := t.TempDir()
+ garbage := filepath.Join(dir, "vector")
+ if err := os.WriteFile(garbage, []byte("#!/bin/sh\necho not a version\n"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := FindVector(garbage); err == nil || !strings.Contains(err.Error(), "could not read a version") {
+ t.Fatalf("expected parse error, got %v", err)
+ }
+}
+
+func TestCompareVersions(t *testing.T) {
+ cases := []struct {
+ a, b string
+ want int
+ }{
+ {"0.56.0", "0.56.0", 0},
+ {"0.57.0", "0.56.0", 1},
+ {"0.55.9", "0.56.0", -1},
+ {"1.0.0", "0.99.9", 1},
+ {"0.56", "0.56.0", 0},
+ }
+ for _, c := range cases {
+ if got := compareVersions(c.a, c.b); got != c.want {
+ t.Errorf("compareVersions(%q,%q) = %d, want %d", c.a, c.b, got, c.want)
+ }
+ }
+}
+
+func TestValidateVectorConfigSurfacesVectorOutput(t *testing.T) {
+ ok := fakeVector(t, "0.56.0", 0)
+ if err := ValidateVectorConfig(ok, "/tmp/x.toml"); err != nil {
+ t.Fatalf("validate ok: %v", err)
+ }
+ bad := fakeVector(t, "0.56.0", 3)
+ if err := ValidateVectorConfig(bad, "/tmp/x.toml"); err == nil || !strings.Contains(err.Error(), "vector validate failed") {
+ t.Fatalf("expected validate failure, got %v", err)
+ }
+}
+
+func TestEnrollmentStoreUsesPrivatePermissionsAndAtomicWrites(t *testing.T) {
+ home := t.TempDir()
+ t.Setenv("HOME", home)
+ if _, err := LoadEnrollment(true); !errors.Is(err, ErrNotEnrolled) {
+ t.Fatalf("expected ErrNotEnrolled, got %v", err)
+ }
+ if err := WriteSecrets(true, "not-a-device-key"); err == nil {
+ t.Fatal("must refuse to store a non-device key")
+ }
+ if err := WriteSecrets(true, "bcn_device_abcdefgh_"+strings.Repeat("k", 43)); err != nil {
+ t.Fatal(err)
+ }
+ info, err := os.Stat(SecretsPath(true))
+ if err != nil || info.Mode().Perm() != 0o600 {
+ t.Fatalf("secrets mode: %v %v", info, err)
+ }
+ entries, _ := os.ReadDir(Dir(true))
+ for _, e := range entries {
+ if strings.HasPrefix(e.Name(), ".") {
+ t.Fatalf("temp file left behind: %s", e.Name())
+ }
+ }
+ key, err := ReadDeviceKey(true)
+ if err != nil || !strings.HasPrefix(key, "bcn_device_abcdefgh_") {
+ t.Fatalf("ReadDeviceKey = %q %v", key, err)
+ }
+ if err := RemoveState(true, false); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := os.Stat(Dir(true)); !os.IsNotExist(err) {
+ t.Fatal("RemoveState should delete the directory")
+ }
+}
diff --git a/cli/beacon/internal/endpoint/config/config.go b/cli/beacon/internal/endpoint/config/config.go
index 368384a3..5ce1db82 100644
--- a/cli/beacon/internal/endpoint/config/config.go
+++ b/cli/beacon/internal/endpoint/config/config.go
@@ -95,14 +95,25 @@ const (
)
type Config struct {
- UserMode bool `json:"user_mode"`
- LogPath string `json:"log_path"`
- Collector Collector `json:"collector"`
- Harnesses []string `json:"harnesses"`
- EventCategories []string `json:"event_categories,omitempty"`
- Inventory *Inventory `json:"inventory_heartbeat,omitempty"`
- Destinations *Destinations `json:"destinations,omitempty"`
- AutoUpdate *AutoUpdate `json:"auto_update,omitempty"`
+ UserMode bool `json:"user_mode"`
+ LogPath string `json:"log_path"`
+ Collector Collector `json:"collector"`
+ Harnesses []string `json:"harnesses"`
+ EventCategories []string `json:"event_categories,omitempty"`
+ Inventory *Inventory `json:"inventory_heartbeat,omitempty"`
+ Destinations *Destinations `json:"destinations,omitempty"`
+ ManagedIngest *ManagedIngest `json:"managed_ingest,omitempty"`
+ AutoUpdate *AutoUpdate `json:"auto_update,omitempty"`
+}
+
+// ManagedIngest records that this endpoint forwards to Asymptote managed ingest. It holds
+// only non-secret identity so status and diagnostics never need the device key, which lives
+// in the 0600 secrets file under the asymptote/ directory and is read only by Vector.
+type ManagedIngest struct {
+ Enabled bool `json:"enabled"`
+ IngestURL string `json:"ingest_url,omitempty"`
+ DeviceID string `json:"device_id,omitempty"`
+ OrganizationID string `json:"organization_id,omitempty"`
}
// AutoUpdate controls Beacon's endpoint update checker. Phase 1 supports
diff --git a/cli/beacon/internal/endpoint/lifecycle/lifecycle.go b/cli/beacon/internal/endpoint/lifecycle/lifecycle.go
index df0df5bf..f94ca164 100644
--- a/cli/beacon/internal/endpoint/lifecycle/lifecycle.go
+++ b/cli/beacon/internal/endpoint/lifecycle/lifecycle.go
@@ -8,6 +8,7 @@ import (
"strings"
"time"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/asymptote"
endpointcollector "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/collector"
endpointconfig "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/config"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/diagnostics"
@@ -73,16 +74,17 @@ type InstallResult struct {
}
type Status struct {
- Version string `json:"version"`
- ConfigPath string `json:"config_path"`
- LogPath string `json:"log_path"`
- RuntimeLog RuntimeLogSource `json:"runtime_log"`
- Collector endpointcollector.Status `json:"collector"`
- Service service.Status `json:"service"`
- Harnesses []harness.Harness `json:"harnesses"`
- Diagnostics []diagnostics.Check `json:"diagnostics"`
- LastEvent string `json:"last_event,omitempty"`
- Destinations DestinationStatus `json:"destinations"`
+ Version string `json:"version"`
+ ConfigPath string `json:"config_path"`
+ LogPath string `json:"log_path"`
+ RuntimeLog RuntimeLogSource `json:"runtime_log"`
+ Collector endpointcollector.Status `json:"collector"`
+ Service service.Status `json:"service"`
+ Harnesses []harness.Harness `json:"harnesses"`
+ Diagnostics []diagnostics.Check `json:"diagnostics"`
+ LastEvent string `json:"last_event,omitempty"`
+ Destinations DestinationStatus `json:"destinations"`
+ ManagedIngest asymptote.ManagedIngestStatus `json:"managed_ingest"`
}
type DestinationStatus struct {
@@ -404,6 +406,13 @@ func Uninstall(opts UninstallOptions) error {
if !cfg.UserMode && !opts.KeepUpdater {
removeUpdaterJob()
}
+ // The managed-ingest forwarder and its credentials go with the endpoint; server-side the
+ // device stays registered until it is revoked from the dashboard.
+ fail("disconnect managed ingest", asymptote.Disconnect(asymptote.DisconnectOptions{
+ UserMode: cfg.UserMode,
+ LogPath: cfg.LogPath,
+ KeepCredentials: opts.KeepConfig,
+ }))
manifest, _ := ReadManifest(cfg.UserMode)
if !opts.KeepConfig {
restoreBackups(manifest.Backups)
@@ -563,16 +572,17 @@ func GetStatus(userMode bool, logPath string) Status {
})
}
return Status{
- Version: version.GetVersion(),
- ConfigPath: endpointconfig.ConfigPath(effectiveCfg.UserMode),
- LogPath: effectiveCfg.LogPath,
- RuntimeLog: runtimeLog,
- Collector: endpointcollector.CheckStatus(effectiveCfg),
- Service: service.Manager{UserMode: effectiveCfg.UserMode}.Status(),
- Harnesses: harness.DiscoverAll(),
- Diagnostics: checks,
- LastEvent: last,
- Destinations: destinationStatus(effectiveCfg),
+ Version: version.GetVersion(),
+ ConfigPath: endpointconfig.ConfigPath(effectiveCfg.UserMode),
+ LogPath: effectiveCfg.LogPath,
+ RuntimeLog: runtimeLog,
+ Collector: endpointcollector.CheckStatus(effectiveCfg),
+ Service: service.Manager{UserMode: effectiveCfg.UserMode}.Status(),
+ Harnesses: harness.DiscoverAll(),
+ Diagnostics: checks,
+ LastEvent: last,
+ Destinations: destinationStatus(effectiveCfg),
+ ManagedIngest: asymptote.Status(effectiveCfg.UserMode, asymptote.StatusOptions{}),
}
}
diff --git a/cli/beacon/internal/endpoint/service/forwarder.go b/cli/beacon/internal/endpoint/service/forwarder.go
new file mode 100644
index 00000000..429a4cee
--- /dev/null
+++ b/cli/beacon/internal/endpoint/service/forwarder.go
@@ -0,0 +1,277 @@
+package service
+
+import (
+ "fmt"
+ "os"
+ "path/filepath"
+ "runtime"
+ "strings"
+)
+
+const (
+ // ForwarderLabel is the launchd label of the Asymptote managed-ingest forwarder. It is a
+ // LaunchAgent for a user-mode endpoint and a LaunchDaemon for a system-mode one.
+ ForwarderLabel = "com.beacon.endpoint.asymptote-forwarder"
+ // ForwarderSystemdUnit is the systemd equivalent, under the user or system scope.
+ ForwarderSystemdUnit = "beacon-asymptote-forwarder.service"
+)
+
+// ForwarderManager manages the long-running Vector process that ships Beacon JSONL to
+// Asymptote. It follows UpdaterManager's shape (unit write/load/unload/status) but is resident
+// like the collector rather than scheduled, and unlike the collector it exists in both user and
+// system modes, because a per-user Beacon install forwards that user's log.
+type ForwarderManager struct {
+ UserMode bool
+ // Kind selects the backend; the zero value auto-detects.
+ Kind Kind
+}
+
+func (m ForwarderManager) resolvedKind() Kind {
+ if m.Kind != KindAuto {
+ return m.Kind
+ }
+ return DetectKind()
+}
+
+// Supported reports whether a supervised forwarder can be installed here.
+//
+// Supervised mode is deliberately not offered: a forwarder nothing restarts would silently stop
+// shipping after the first crash or reboot, which is worse than telling the operator to run the
+// pack's vector.toml under their own supervisor.
+func (m ForwarderManager) Supported() bool {
+ switch m.resolvedKind() {
+ case KindLaunchd:
+ return runtime.GOOS == "darwin"
+ case KindSystemd:
+ return systemdIsInit()
+ default:
+ return false
+ }
+}
+
+// UnsupportedReason explains why Supported is false.
+func (m ForwarderManager) UnsupportedReason() string {
+ switch m.resolvedKind() {
+ case KindLaunchd:
+ return "launchd service management is supported only on macOS"
+ case KindSystemd:
+ return "systemd is not PID 1 on this host, so the forwarder cannot be installed as a service"
+ default:
+ return "the Asymptote forwarder needs launchd or systemd to stay running; on this host run Vector yourself with the config from `beacon endpoint asymptote install-pack`"
+ }
+}
+
+// Label is the service identifier for status output.
+func (m ForwarderManager) Label() string {
+ if m.resolvedKind() == KindSystemd {
+ return ForwarderSystemdUnit
+ }
+ return ForwarderLabel
+}
+
+// UnitPath returns where the forwarder's service definition lives.
+func (m ForwarderManager) UnitPath() (string, error) {
+ switch m.resolvedKind() {
+ case KindSystemd:
+ if m.UserMode {
+ home, err := os.UserHomeDir()
+ if err != nil {
+ return "", err
+ }
+ return filepath.Join(home, ".config", "systemd", "user", ForwarderSystemdUnit), nil
+ }
+ return filepath.Join("/etc/systemd/system", ForwarderSystemdUnit), nil
+ default:
+ if m.UserMode {
+ home, err := os.UserHomeDir()
+ if err != nil {
+ return "", err
+ }
+ return filepath.Join(home, "Library", "LaunchAgents", ForwarderLabel+".plist"), nil
+ }
+ return filepath.Join("/Library/LaunchDaemons", ForwarderLabel+".plist"), nil
+ }
+}
+
+// RemoveUnits deletes the service definition. Missing files are not an error.
+func (m ForwarderManager) RemoveUnits() {
+ if path, err := m.UnitPath(); err == nil {
+ _ = os.Remove(path)
+ }
+}
+
+// WriteUnit installs a service definition that runs `vectorBin --config configPath`.
+func (m ForwarderManager) WriteUnit(vectorBin, configPath string) (string, error) {
+ if !m.Supported() {
+ return "", fmt.Errorf("%s", m.UnsupportedReason())
+ }
+ path, err := m.UnitPath()
+ if err != nil {
+ return "", err
+ }
+ if err := ensureDir(path); err != nil {
+ return "", err
+ }
+ var content string
+ if m.resolvedKind() == KindSystemd {
+ content = forwarderUnitFile(vectorBin, configPath, m.UserMode)
+ } else {
+ content = forwarderPlist(ForwarderLabel, vectorBin, configPath)
+ }
+ if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
+ return "", err
+ }
+ if m.resolvedKind() == KindSystemd {
+ if out, err := runSystemctlCommand(systemctlArgs(m.UserMode, "daemon-reload")...); err != nil {
+ return path, systemctlError(out, err, "daemon-reload")
+ }
+ }
+ return path, nil
+}
+
+// Load registers and starts the forwarder. An already-loaded launchd job is re-bootstrapped so a
+// rewritten config takes effect.
+func (m ForwarderManager) Load() error {
+ if !m.Supported() {
+ return fmt.Errorf("%s", m.UnsupportedReason())
+ }
+ if m.resolvedKind() == KindSystemd {
+ if out, err := runSystemctlCommand(systemctlArgs(m.UserMode, "enable", "--now", ForwarderSystemdUnit)...); err != nil {
+ return systemctlError(out, err, "enable --now "+ForwarderSystemdUnit)
+ }
+ if out, err := runSystemctlCommand(systemctlArgs(m.UserMode, "restart", ForwarderSystemdUnit)...); err != nil {
+ return systemctlError(out, err, "restart "+ForwarderSystemdUnit)
+ }
+ return nil
+ }
+ path, err := m.UnitPath()
+ if err != nil {
+ return err
+ }
+ domain := serviceDomain(m.UserMode)
+ // bootout first so a config rewrite (re-enrollment rotates the key) restarts Vector.
+ _ = runLaunchctlWithContext(domain, ForwarderLabel, "", "bootout", domain+"/"+ForwarderLabel)
+ return loadLaunchdJob(domain, ForwarderLabel, path)
+}
+
+// Unload stops and deregisters the forwarder. A missing unit is not an error.
+func (m ForwarderManager) Unload() error {
+ switch m.resolvedKind() {
+ case KindSystemd:
+ if !systemdIsInit() {
+ return nil
+ }
+ if out, err := runSystemctlCommand(systemctlArgs(m.UserMode, "stop", ForwarderSystemdUnit)...); err != nil && !systemdUnitMissing(out) {
+ return systemctlError(out, err, "stop "+ForwarderSystemdUnit)
+ }
+ if out, err := runSystemctlCommand(systemctlArgs(m.UserMode, "disable", ForwarderSystemdUnit)...); err != nil && !systemdUnitMissing(out) {
+ return systemctlError(out, err, "disable "+ForwarderSystemdUnit)
+ }
+ return nil
+ case KindLaunchd:
+ if runtime.GOOS != "darwin" {
+ return nil
+ }
+ domain := serviceDomain(m.UserMode)
+ return runLaunchctlWithContext(domain, ForwarderLabel, "", "bootout", domain+"/"+ForwarderLabel)
+ default:
+ return nil
+ }
+}
+
+// Status reports whether the forwarder is loaded and running.
+func (m ForwarderManager) Status() Status {
+ kind := m.resolvedKind()
+ if !m.Supported() {
+ return Status{Label: m.Label(), Kind: string(kind), Message: m.UnsupportedReason()}
+ }
+ if kind == KindSystemd {
+ status := Status{Label: ForwarderSystemdUnit, Kind: string(KindSystemd)}
+ enabledOut, _ := runSystemctlCommand(systemctlArgs(m.UserMode, "is-enabled", ForwarderSystemdUnit)...)
+ switch strings.TrimSpace(enabledOut) {
+ case "enabled", "enabled-runtime", "static":
+ status.Loaded = true
+ }
+ activeOut, _ := runSystemctlCommand(systemctlArgs(m.UserMode, "is-active", ForwarderSystemdUnit)...)
+ status.Running = strings.TrimSpace(activeOut) == "active"
+ if status.Running {
+ status.Loaded = true
+ }
+ if !status.Loaded && !status.Running {
+ status.Message = "forwarder not installed"
+ }
+ return status
+ }
+ status := Status{Label: ForwarderLabel, Kind: string(KindLaunchd)}
+ out, err := runLaunchctlCommand("print", serviceDomain(m.UserMode)+"/"+ForwarderLabel)
+ if err != nil {
+ status.Message = strings.TrimSpace(out)
+ return status
+ }
+ status.Loaded = true
+ status.Running = strings.Contains(out, "state = running") || strings.Contains(out, "pid =")
+ return status
+}
+
+// forwarderUnitFile renders the systemd unit. Vector reads its own config, so the unit needs no
+// environment; the rendered vector.toml carries literal paths and URLs.
+func forwarderUnitFile(vectorBin, configPath string, userMode bool) string {
+ var b strings.Builder
+ b.WriteString("[Unit]\n")
+ b.WriteString("Description=Beacon endpoint forwarder to Asymptote managed ingest\n")
+ b.WriteString("Documentation=https://docs.asymptotelabs.ai/cli/endpoint-connect\n")
+ b.WriteString("After=network-online.target\n")
+ b.WriteString("Wants=network-online.target\n")
+ b.WriteString("\n[Service]\n")
+ b.WriteString("Type=simple\n")
+ fmt.Fprintf(&b, "ExecStart=%s --config %s\n", systemdArg(vectorBin), systemdArg(configPath))
+ b.WriteString("Restart=always\n")
+ b.WriteString("RestartSec=5\n")
+ b.WriteString("StandardOutput=journal\n")
+ b.WriteString("StandardError=journal\n")
+ if !userMode {
+ // System mode reads /var/log/beacon-agent, which root owns.
+ b.WriteString("User=root\n")
+ }
+ b.WriteString("\n[Install]\n")
+ if userMode {
+ b.WriteString("WantedBy=default.target\n")
+ } else {
+ b.WriteString("WantedBy=multi-user.target\n")
+ }
+ return b.String()
+}
+
+// forwarderPlist renders the launchd job: resident, restarted by launchd, started at load.
+func forwarderPlist(label, vectorBin, configPath string) string {
+ return fmt.Sprintf(`<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>Label</key>
+ <string>%s</string>
+ <key>ProgramArguments</key>
+ <array>
+ <string>%s</string>
+ <string>--config</string>
+ <string>%s</string>
+ </array>
+ <key>RunAtLoad</key>
+ <true/>
+ <key>KeepAlive</key>
+ <true/>
+ <key>ThrottleInterval</key>
+ <integer>10</integer>
+ <key>StandardOutPath</key>
+ <string>/tmp/%s.out</string>
+ <key>StandardErrorPath</key>
+ <string>/tmp/%s.err</string>
+</dict>
+</plist>
+`, xmlEscape(label), xmlEscape(vectorBin), xmlEscape(configPath), xmlEscape(label), xmlEscape(label))
+}
+
+func xmlEscape(s string) string {
+ replacer := strings.NewReplacer("&", "&amp;", "<", "&lt;", ">", "&gt;", `"`, "&quot;")
+ return replacer.Replace(s)
+}
diff --git a/cli/beacon/internal/endpoint/service/forwarder_test.go b/cli/beacon/internal/endpoint/service/forwarder_test.go
new file mode 100644
index 00000000..78a568a2
--- /dev/null
+++ b/cli/beacon/internal/endpoint/service/forwarder_test.go
@@ -0,0 +1,102 @@
+package service
+
+import (
+ "path/filepath"
+ "runtime"
+ "strings"
+ "testing"
+)
+
+func TestForwarderPlistRunsVectorResidentWithKeepAlive(t *testing.T) {
+ got := forwarderPlist(ForwarderLabel, "/opt/beacon/bin/vector", "/Users/me/.beacon/endpoint/asymptote/vector.toml")
+ for _, want := range []string{
+ "<string>com.beacon.endpoint.asymptote-forwarder</string>",
+ "<string>/opt/beacon/bin/vector</string>",
+ "<string>--config</string>",
+ "<string>/Users/me/.beacon/endpoint/asymptote/vector.toml</string>",
+ "<key>RunAtLoad</key>\n <true/>",
+ "<key>KeepAlive</key>\n <true/>",
+ "<key>ThrottleInterval</key>",
+ } {
+ if !strings.Contains(got, want) {
+ t.Fatalf("plist missing %q:\n%s", want, got)
+ }
+ }
+ if strings.Contains(got, "StartCalendarInterval") {
+ t.Fatal("forwarder must be resident, not scheduled")
+ }
+ escaped := forwarderPlist("l", "/tmp/a&b", "/tmp/<c>.toml")
+ if !strings.Contains(escaped, "/tmp/a&amp;b") || !strings.Contains(escaped, "&lt;c&gt;") {
+ t.Fatalf("plist must XML-escape paths:\n%s", escaped)
+ }
+}
+
+func TestForwarderSystemdUnitRestartsAlwaysAndScopesByMode(t *testing.T) {
+ system := forwarderUnitFile("/usr/bin/vector", "/var/lib/beacon/asymptote/vector.toml", false)
+ for _, want := range []string{
+ `ExecStart="/usr/bin/vector" --config "/var/lib/beacon/asymptote/vector.toml"`,
+ "Restart=always",
+ "After=network-online.target",
+ "User=root",
+ "WantedBy=multi-user.target",
+ } {
+ if !strings.Contains(system, want) {
+ t.Fatalf("system unit missing %q:\n%s", want, system)
+ }
+ }
+ user := forwarderUnitFile("/usr/bin/vector", "/home/me/.beacon/endpoint/asymptote/vector.toml", true)
+ if strings.Contains(user, "User=root") || !strings.Contains(user, "WantedBy=default.target") {
+ t.Fatalf("user unit must not run as root and must hook default.target:\n%s", user)
+ }
+}
+
+func TestForwarderUnitPathFollowsBackendAndMode(t *testing.T) {
+ t.Setenv("HOME", "/home/tester")
+ cases := []struct {
+ kind Kind
+ userMode bool
+ want string
+ }{
+ {KindLaunchd, true, filepath.Join("/home/tester", "Library", "LaunchAgents", ForwarderLabel+".plist")},
+ {KindLaunchd, false, filepath.Join("/Library/LaunchDaemons", ForwarderLabel+".plist")},
+ {KindSystemd, true, filepath.Join("/home/tester", ".config", "systemd", "user", ForwarderSystemdUnit)},
+ {KindSystemd, false, filepath.Join("/etc/systemd/system", ForwarderSystemdUnit)},
+ }
+ for _, c := range cases {
+ got, err := ForwarderManager{UserMode: c.userMode, Kind: c.kind}.UnitPath()
+ if err != nil || got != c.want {
+ t.Errorf("%s user=%t: got %q (%v), want %q", c.kind, c.userMode, got, err, c.want)
+ }
+ }
+ if (ForwarderManager{Kind: KindSystemd}).Label() != ForwarderSystemdUnit || (ForwarderManager{Kind: KindLaunchd}).Label() != ForwarderLabel {
+ t.Fatal("labels must follow the backend")
+ }
+}
+
+func TestForwarderRefusesSupervisedAndForeignBackends(t *testing.T) {
+ m := ForwarderManager{Kind: KindSupervised}
+ if m.Supported() {
+ t.Fatal("supervised mode has no supervisor; the forwarder must refuse it")
+ }
+ if !strings.Contains(m.UnsupportedReason(), "install-pack") {
+ t.Fatalf("unsupported reason should point at the pack: %s", m.UnsupportedReason())
+ }
+ if _, err := m.WriteUnit("/usr/bin/vector", "/tmp/vector.toml"); err == nil {
+ t.Fatal("WriteUnit must fail when unsupported")
+ }
+ if err := m.Load(); err == nil {
+ t.Fatal("Load must fail when unsupported")
+ }
+ if err := m.Unload(); err != nil {
+ t.Fatalf("Unload must be a no-op when unsupported, got %v", err)
+ }
+ status := m.Status()
+ if status.Loaded || status.Running || status.Message == "" {
+ t.Fatalf("status = %+v", status)
+ }
+ if runtime.GOOS != "darwin" {
+ if (ForwarderManager{Kind: KindLaunchd}).Supported() {
+ t.Fatal("launchd must be unsupported off macOS")
+ }
+ }
+}
diff --git a/docs/architecture/managed-architecture.mdx b/docs/architecture/managed-architecture.mdx
index 3d3daaeb..136133f4 100644
--- a/docs/architecture/managed-architecture.mdx
+++ b/docs/architecture/managed-architecture.mdx
@@ -19,6 +19,16 @@ Use this architecture when agent activity needs to be visible across teams, endp
4. **Governance layer:** Policy controls, identity mapping, approvals, SSO, RBAC, and audit trails connect runtime activity to users, teams, and security workflows.
5. **Investigation workflows:** Timelines and case workflows organize prompts, tool calls, file access, command execution, and related context for review.
+## How endpoint telemetry reaches Asymptote
+
+Beacon on the endpoint stays a local JSONL producer. `beacon endpoint connect` adds the managed path:
+
+1. **Approval.** The CLI registers the machine's hostname, OS and Beacon version and opens the dashboard's approval page. A member of the organization signs in with Clerk, picks the organization, and clicks Approve. Only organizations Asymptote has enabled for managed ingest can approve devices.
+2. **Device key.** The CLI redeems a one-time code with a PKCE verifier and receives a key for this one device. The key is stored in a `0600` secrets file and read only by Vector; it is never in Beacon's config or the process environment. Revoking the device, or removing the approving user from the organization, invalidates it within about a minute.
+3. **Forwarding.** A Vector service tails `runtime.jsonl` (from the point of approval) and `inventory_state.jsonl` and POSTs gzip NDJSON batches to Asymptote's ingest service with the device key. A disk buffer covers offline periods.
+4. **Ingest.** The service verifies the key, the approver's membership and the organization's enablement, validates each line, stamps a `tenant` block (organization, device, approving user, receive time) server-side, and writes one object per batch under `orgs/<organization>/<stream>/date=…/` in Asymptote's bucket.
+5. **Per-organization tables.** Each object triggers a notification; the organization's own ClickPipe loads it into that organization's ClickHouse tables. The dashboard resolves an organization to its tables through a mapping row, so tenant isolation is a table boundary, and duplicates from retried batches collapse on Beacon's deterministic event id.
+
## Managed capabilities
| Capability | Purpose |
diff --git a/docs/changelog/cli.mdx b/docs/changelog/cli.mdx
index 348d9b0a..7619c796 100644
--- a/docs/changelog/cli.mdx
+++ b/docs/changelog/cli.mdx
@@ -13,6 +13,16 @@ Stay up to date with the latest changes to the Agent Beacon CLI.
### Unreleased
+- **`beacon endpoint connect` and `disconnect`** · Connect an endpoint to
+ Asymptote managed ingest from the CLI: it finds Vector (0.56+), opens the
+ dashboard's device approval page, receives a per-device key through a
+ loopback PKCE exchange, stores it in a `0600` secrets file, renders and
+ validates the forwarder config, and starts `com.beacon.endpoint.asymptote-forwarder`
+ (launchd) or `beacon-asymptote-forwarder.service` (systemd) in user or system
+ mode. `beacon endpoint status` gains an "Asymptote managed ingest" line and a
+ `managed_ingest` JSON object with forwarder state and a live credential check;
+ `config.json` gains a non-secret `managed_ingest` block; uninstall removes the
+ forwarder and credentials. Re-running connect rotates the key in place.
- **Asymptote Managed forwarding pack** · `beacon endpoint asymptote` generates a
Vector `http` forwarder that posts the runtime and inventory JSONL to
Asymptote's ingest service with a per-device key read from a `0600` secrets
diff --git a/docs/cli/endpoint-connect.mdx b/docs/cli/endpoint-connect.mdx
new file mode 100644
index 00000000..8c8becae
--- /dev/null
+++ b/docs/cli/endpoint-connect.mdx
@@ -0,0 +1,111 @@
+---
+title: "beacon endpoint connect"
+description: "Connect a Beacon endpoint to Asymptote managed ingest, or disconnect it, and understand what the forwarder stores and sends."
+---
+
+## Command overview
+
+`beacon endpoint connect` forwards this endpoint's telemetry to Asymptote so it appears on the Asymptote dashboard. It opens the dashboard in your browser, where a member of your organization approves this specific device; the CLI then receives a key for this device, stores it in a private secrets file, and starts a Vector forwarder that ships the runtime and inventory JSONL over HTTPS.
+
+Forwarding is opt-in and revocable. Beacon's default stays local-only, nothing recorded before the approval is sent, and revoking the device from the dashboard stops ingestion within about a minute. `beacon endpoint disconnect` stops the forwarder and removes the local credentials.
+
+```bash title="Command syntax"
+beacon endpoint connect [flags]
+beacon endpoint disconnect [flags]
+```
+
+## Prerequisites
+
+- Beacon endpoint installed (`beacon endpoint install`) and writing local JSONL.
+- Vector 0.56 or newer on the machine. The signed macOS package installs it at `/opt/beacon/bin/vector`; Homebrew provides it as `vector` (the Beacon formula depends on it); on Linux install the `vector` package from [vector.dev](https://vector.dev). `connect` stops before opening a browser if no usable Vector is found.
+- A browser where you can sign in to the Asymptote dashboard as a member of an organization that has managed ingest enabled.
+
+## What connect does
+
+1. Locates Vector: `--vector-bin`, then `BEACON_VECTOR_BIN`, then `/opt/beacon/bin/vector`, the Homebrew prefixes, then `PATH`.
+2. Registers this machine's hostname, operating system, architecture, Beacon version and install mode with the dashboard, and opens `/cli/enroll` in your browser. The approval page shows those details; nothing is minted until someone clicks **Approve this device**.
+3. Receives the device key through a loopback callback and a PKCE exchange. The key is written once to `asymptote/vector-secrets.json` with mode `0600` and is never printed.
+4. Renders `asymptote/vector.toml` from the [Asymptote pack](/cli/asymptote) template with the ingest URL returned by enrollment, runs `vector validate`, installs a service unit and starts it.
+5. Records the non-secret enrollment (device id, organization, ingest URL) in `asymptote/enrollment.json` and `config.json`'s `managed_ingest` block.
+
+Re-running `connect` on a connected machine reuses its install id, so the server rotates the existing device's key in place instead of creating a second device.
+
+## Files and services
+
+| Item | User mode | System mode (macOS) | System mode (Linux) |
+|------|-----------|---------------------|---------------------|
+| Enrollment record | `~/.beacon/endpoint/asymptote/enrollment.json` (0600) | `/Library/Application Support/Beacon/Endpoint/asymptote/enrollment.json` | `/etc/beacon/endpoint/asymptote/enrollment.json` |
+| Device key | `~/.beacon/endpoint/asymptote/vector-secrets.json` (0600) | `…/Endpoint/asymptote/vector-secrets.json` | `/etc/beacon/endpoint/asymptote/vector-secrets.json` |
+| Vector config | `~/.beacon/endpoint/asymptote/vector.toml` (0644, no secret) | `…/Endpoint/asymptote/vector.toml` | `/etc/beacon/endpoint/asymptote/vector.toml` |
+| Buffer and checkpoints | `~/.beacon/endpoint/asymptote/vector-data/` | `…/Endpoint/asymptote/vector-data/` | `/etc/beacon/endpoint/asymptote/vector-data/` |
+| Service | `~/Library/LaunchAgents/com.beacon.endpoint.asymptote-forwarder.plist` | `/Library/LaunchDaemons/com.beacon.endpoint.asymptote-forwarder.plist` | `/etc/systemd/system/beacon-asymptote-forwarder.service` (user mode: `~/.config/systemd/user/`) |
+
+The directory is `0700`. The device key appears only in the secrets file, which Vector reads through its `file` secret backend; it is in neither `vector.toml`, `config.json`, nor the forwarder's environment.
+
+## Flags
+
+| Flag | Description |
+|------|-------------|
+| `--dashboard-url <url>` | Asymptote dashboard URL. Defaults to `https://asymptotelabs.ai` or `BEACON_DASHBOARD_URL`. Must be `https://` |
+| `--no-browser` | Print the approval URL instead of opening a browser |
+| `--vector-bin <path>` | Vector binary to run |
+| `--user` | Use per-user endpoint paths. Enabled by default |
+| `--system` | Use system endpoint paths and a LaunchDaemon or system unit. Requires root; the browser opens as the active console user |
+| `--log-path <path>` | Runtime JSONL log path |
+| `--json` | Print the result as JSON (the device key is never included) |
+
+`disconnect` accepts the same path flags plus `--keep-credentials`, which keeps the enrollment record and device key so a later `connect` can reuse this device without a new approval.
+
+## Examples
+
+```bash title="Connect the default per-user install"
+beacon endpoint connect
+```
+
+```bash title="Connect a system-mode install from the signed package"
+sudo /opt/beacon/bin/beacon endpoint connect --system
+```
+
+```bash title="Connect from a machine without a browser"
+beacon endpoint connect --no-browser
+# open the printed URL in a browser where you are signed in
+```
+
+```bash title="Stop forwarding and remove the local credentials"
+beacon endpoint disconnect
+```
+
+## Checking the connection
+
+`beacon endpoint status` prints one line for managed ingest: whether this endpoint is connected, to which organization, the device id, whether the forwarder service is loaded and running, whether the credential is still valid (it asks the ingest service, with a 3-second timeout), and the size of the disk buffer. `--json` exposes the same under `managed_ingest`.
+
+```text
+Asymptote managed ingest: connected to Asymptote Test as device 807c6a11-…; forwarder loaded=true running=true; credential valid
+```
+
+`credential revoked` means the key was revoked or expired, or the approving user is no longer a member of the organization; Vector is logging 401s and dropping batches. Run `beacon endpoint connect` again to re-enroll.
+
+## Revocation and disconnect
+
+Revoke a device, or every device a person approved, from the dashboard's **Beacon Endpoints** page. The ingest service rejects the key within about a minute. `disconnect` is the local half: it stops and removes the forwarder and its config and, unless `--keep-credentials` is given, the enrollment record and device key. `beacon endpoint uninstall` does the same as part of removing the endpoint. Neither revokes the device server-side; the CLI tells you where to do that.
+
+## Offline behavior
+
+Vector keeps reading into an on-disk buffer (512 MiB for runtime, 256 MiB for inventory) while the network is unavailable and drains it when connectivity returns. The ingest service accepts old timestamps and the dashboard collapses re-sent duplicates on Beacon's deterministic event id, so a laptop that was asleep or offline catches up without loss or double counting, up to the buffer size.
+
+## Related
+
+<Columns cols={2}>
+ <Card title="Asymptote Managed forwarding" icon="tower-broadcast" href="/log-forwarding/asymptote">
+ Wire contract, what leaves the machine, revocation, and offline behavior.
+ </Card>
+ <Card title="beacon endpoint asymptote" icon="terminal" href="/cli/asymptote">
+ The forwarder pack, for running Vector by hand.
+ </Card>
+ <Card title="Endpoint status" icon="heart-pulse" href="/cli/endpoint-status">
+ Inspect the forwarder and credential state.
+ </Card>
+ <Card title="Endpoint paths" icon="folder-tree" href="/cli/endpoint-paths">
+ Every file and service Beacon writes.
+ </Card>
+</Columns>
diff --git a/docs/cli/endpoint-paths.mdx b/docs/cli/endpoint-paths.mdx
index 981e26ff..db0aa413 100644
--- a/docs/cli/endpoint-paths.mdx
+++ b/docs/cli/endpoint-paths.mdx
@@ -15,6 +15,7 @@ Beacon manages different paths depending on whether you install in user mode or
| Rotated runtime archives | `~/.beacon/endpoint/logs/runtime.jsonl.1` through `.5` | `/var/log/beacon-agent/runtime.jsonl.1` through `.5` | `/var/log/beacon-agent/runtime.jsonl.1` through `.5` | `%ProgramData%\Beacon\Endpoint\logs\runtime.jsonl.1` through `.5` |
| Threat rule store | `~/.beacon/endpoint/rules` | `/Library/Application Support/Beacon/Endpoint/rules` | `/etc/beacon/endpoint/rules` | `%ProgramData%\Beacon\Endpoint\rules` |
| Collector config | `~/.beacon/endpoint/otelcol.yaml` | `/Library/Application Support/Beacon/Endpoint/otelcol.yaml` | `/etc/beacon/endpoint/otelcol.yaml` | `%ProgramData%\Beacon\Endpoint\otelcol.yaml` |
+| Managed-ingest state (`beacon endpoint connect`) | `~/.beacon/endpoint/asymptote/` (`enrollment.json`, `vector-secrets.json`, `vector.toml`, `vector-data/`) | `/Library/Application Support/Beacon/Endpoint/asymptote/` | `/etc/beacon/endpoint/asymptote/` | Not yet supported |
| Installed binaries | None | `/opt/beacon/bin` | `/opt/beacon/bin` | `%ProgramFiles%\Beacon\bin` |
| OTLP gRPC | `127.0.0.1:4317` | `127.0.0.1:4317` | `127.0.0.1:4317` | `127.0.0.1:4317` |
| OTLP HTTP | `127.0.0.1:4318` | `127.0.0.1:4318` | `127.0.0.1:4318` | `127.0.0.1:4318` |
@@ -32,6 +33,8 @@ The collector runs under whichever service manager the host provides. On Linux,
| Windows | Service Control Manager | `BeaconCollector` service, defined at `HKLM\SYSTEM\CurrentControlSet\Services\BeaconCollector` | Supervised, because Windows has no per-user service manager |
| Containers, no init | supervised | `/etc/beacon/endpoint/collector.pid` | `~/.beacon/endpoint/collector.pid` |
+The Asymptote forwarder started by `beacon endpoint connect` is a second, resident service that runs Vector: `/Library/LaunchDaemons/com.beacon.endpoint.asymptote-forwarder.plist` or `~/Library/LaunchAgents/com.beacon.endpoint.asymptote-forwarder.plist` on macOS, `/etc/systemd/system/beacon-asymptote-forwarder.service` or `~/.config/systemd/user/beacon-asymptote-forwarder.service` on Linux. It is not offered in supervised mode, because nothing would restart it; run the [Asymptote pack](/cli/asymptote) under your own supervisor there.
+
Windows has no unit file to point at: the service definition lives in the registry, so that is what `beacon endpoint status` reports where the other platforms report a path. And there is no counterpart to `systemctl --user` or launchd's per-user domain, so a Windows user-mode install always gets the supervised collector. See [Windows install](/platforms/windows#user-mode-install).
A supervised collector is a plain background process tracked by a pidfile. It works, but nothing restarts it if it exits or when the machine reboots. `beacon endpoint status` says so explicitly rather than reporting the same health as a real service.
diff --git a/docs/cli/endpoint-status.mdx b/docs/cli/endpoint-status.mdx
index bd5000fc..63bda880 100644
--- a/docs/cli/endpoint-status.mdx
+++ b/docs/cli/endpoint-status.mdx
@@ -61,6 +61,7 @@ Status includes:
- Endpoint diagnostics
- Destination configuration in JSON output, including Splunk HEC or Falcon LogScale HEC endpoint, index, source, and sourcetype when configured
- Last Beacon event in the runtime log, when present
+- Asymptote managed ingest: whether this endpoint is connected, the organization and device id, forwarder service state, whether the device key is still accepted by the ingest service (`valid`, `revoked`, or `unknown` when offline), and the disk buffer size. In `--json` this is the `managed_ingest` object; the device key itself is never included.
When Splunk HEC is configured, `--json` includes a `destinations.splunk_hec` object with `configured: true` and the non-secret destination settings. When Falcon LogScale HEC is configured, `--json` includes `destinations.falcon_hec` with the same non-secret fields. HEC tokens are not printed. File-based destinations such as Wazuh, Elastic, Datadog, Sumo Logic, Rapid7, Microsoft Sentinel, and AWS S3 validate against the configured runtime log path and their generated shipper configuration.
diff --git a/docs/cli/endpoint-uninstall.mdx b/docs/cli/endpoint-uninstall.mdx
index 6b7ac66f..9e78cb08 100644
--- a/docs/cli/endpoint-uninstall.mdx
+++ b/docs/cli/endpoint-uninstall.mdx
@@ -59,6 +59,8 @@ sudo beacon endpoint uninstall --system --keep-logs
Beacon removes files listed in its install manifest, including managed config, collector config, and service files. Unless `--keep-logs` is set, it also removes the configured runtime JSONL log.
+If the endpoint was connected to Asymptote managed ingest, uninstall also stops and removes the `com.beacon.endpoint.asymptote-forwarder` service (or `beacon-asymptote-forwarder.service`) and the `asymptote/` directory holding the Vector config, buffer, enrollment record and device key; `--keep-config` keeps the enrollment record and key. The device stays registered server-side until it is revoked from the dashboard's Beacon Endpoints page.
+
## Related
<Columns cols={2}>
diff --git a/docs/cli/index.mdx b/docs/cli/index.mdx
index 4f86fde6..7af6b541 100644
--- a/docs/cli/index.mdx
+++ b/docs/cli/index.mdx
@@ -143,7 +143,9 @@ Manage the local endpoint agent and inspect supported agent harness telemetry.
| Command | Description |
|---------|-------------|
| [`beacon endpoint install`](/cli/endpoint-install) | Install or update the local endpoint collector, runtime telemetry configuration, and optional Splunk HEC or Falcon LogScale HEC forwarding. |
-| [`beacon endpoint status`](/cli/endpoint-status) | Inspect collector health, runtime log state, configured harnesses, diagnostics, and forwarding readiness. |
+| [`beacon endpoint status`](/cli/endpoint-status) | Inspect collector health, runtime log state, configured harnesses, diagnostics, forwarding readiness, and the Asymptote managed-ingest connection. |
+| [`beacon endpoint connect`](/cli/endpoint-connect) | Approve this device in the Asymptote dashboard and start the Vector forwarder to managed ingest. |
+| [`beacon endpoint disconnect`](/cli/endpoint-connect) | Stop the Asymptote forwarder and remove the local device key. |
| [`beacon endpoint doctor`](/cli/endpoint-doctor) | Run local endpoint health checks with pass/fail exit behavior and optional safe remediation. |
| [`beacon endpoint inventory`](/cli/endpoint-inventory) | Show configured, detected, hook, and observed endpoint inventory. |
| [`beacon endpoint discover`](/cli/endpoint-discover) | Discover supported local [agent harnesses](/runtimes) and their telemetry configuration state. |
diff --git a/docs/docs.json b/docs/docs.json
index de262001..eba5b37c 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -372,6 +372,7 @@
"root": "cli/endpoint",
"pages": [
"cli/endpoint-install",
+ "cli/endpoint-connect",
"cli/endpoint-status",
"cli/endpoint-doctor",
"cli/endpoint-inventory",
diff --git a/docs/security/endpoint-operations.mdx b/docs/security/endpoint-operations.mdx
index 9b622394..929aa98f 100644
--- a/docs/security/endpoint-operations.mdx
+++ b/docs/security/endpoint-operations.mdx
@@ -81,8 +81,9 @@ Optional network behavior is customer configured:
| Falcon LogScale HEC | Optional collector exporter sends events to the configured Falcon LogScale HEC endpoint |
| Endpoint self-update | Optional updater mode fetches the release manifest and signed package assets when manually invoked or explicitly enabled |
| Customer-managed forwarding | Customer shipper, agent, or SIEM pipeline reads local JSONL |
+| Asymptote managed ingest (opt-in) | After a member of the organization approves the device in the browser (`beacon endpoint connect`), a Vector forwarder posts the runtime and inventory JSONL over HTTPS to Asymptote's ingest service with a per-device key; revocable from the dashboard, effective within about a minute |
-Beacon itself does not store Elastic cluster URLs or credentials, Datadog API keys or site configuration, Sumo Source URLs, tokens, collector configuration, or Rapid7 webhook URLs. Splunk HEC and Falcon LogScale HEC tokens are stored only in local collector configuration when those optional destinations are enabled.
+Beacon itself does not store Elastic cluster URLs or credentials, Datadog API keys or site configuration, Sumo Source URLs, tokens, collector configuration, or Rapid7 webhook URLs. Splunk HEC and Falcon LogScale HEC tokens are stored only in local collector configuration when those optional destinations are enabled. The Asymptote device key is stored only in `asymptote/vector-secrets.json` (mode `0600`, inside a `0700` directory) under the endpoint base directory, read by Vector through its secret backend; `config.json` holds only the non-secret device and organization ids, and the key is never printed by any command.
Endpoint package self-updates are off by default. When an admin enables
`check-only` or `auto`, the updater's network access is limited to the configured
@@ -91,7 +92,7 @@ local-only.
## Uninstall guarantees
-`beacon endpoint uninstall` unloads the local Beacon service and removes managed endpoint files. Beacon removes files listed in its install manifest, including managed config, collector config, and service files. Unless `--keep-logs` is set, it also removes the configured runtime JSONL log.
+`beacon endpoint uninstall` unloads the local Beacon service and removes managed endpoint files. Beacon removes files listed in its install manifest, including managed config, collector config, and service files. Unless `--keep-logs` is set, it also removes the configured runtime JSONL log. A connected endpoint's Asymptote forwarder service and `asymptote/` directory (Vector config, buffer, enrollment record, device key) are removed too; `beacon endpoint disconnect` does only that part.
Use retention flags when you intentionally want to preserve evidence or configuration:
diff --git a/docs/security/retention-redaction.mdx b/docs/security/retention-redaction.mdx
index 143715d9..5ef12000 100644
--- a/docs/security/retention-redaction.mdx
+++ b/docs/security/retention-redaction.mdx
@@ -75,7 +75,10 @@ and customer-managed shippers read the resulting local JSONL. Supported cloud
agents upload a compressed snapshot of their sandbox-local JSONL directly to
customer-managed GCS or S3. Splunk HEC and Falcon LogScale HEC forwarding
receive the same normalized collector output according to the configured
-endpoint pipeline.
+endpoint pipeline. Asymptote managed ingest, when a device has been connected,
+forwards the runtime and inventory JSONL lines written after approval exactly as
+stored locally, so the same retention and redaction settings govern what
+reaches the Asymptote dashboard.
Review runtime scope, artifact access, destination permissions, and downstream retention before rollout so retained content matches your approved telemetry policy.
diff --git a/packaging/macos/README.md b/packaging/macos/README.md
index afdde470..bdea8c6c 100644
--- a/packaging/macos/README.md
+++ b/packaging/macos/README.md
@@ -37,6 +37,15 @@ The endpoint install creates system configuration and runtime state:
/var/log/beacon-agent/runtime.jsonl
```
+Connecting a system-mode endpoint to Asymptote managed ingest
+(`sudo /opt/beacon/bin/beacon endpoint connect --system`) opens the approval page
+in the active console user's browser and then adds a second resident service,
+`com.beacon.endpoint.asymptote-forwarder` (`/Library/LaunchDaemons/…plist`),
+running the bundled `/opt/beacon/bin/vector` with the config, disk buffer,
+enrollment record and `0600` device key below
+`/Library/Application Support/Beacon/Endpoint/asymptote/`. `beacon endpoint
+disconnect --system` and `beacon endpoint uninstall --system` remove it.
+
The package postinstall also repairs endpoint user configuration for the active
console user when one is logged in. This user-context step points Claude Code and
Codex native OTLP settings at the system collector and refreshes supported user