diff --git a/.golangci.yml b/.golangci.yml index 90eea92..25e304d 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -93,6 +93,9 @@ linters: misspell: locale: US + ignore-rules: + # The SSP telemetry contract spells this outcome with two l's. + - cancelled errorlint: # %w wrapping is preferred but legacy %v errors are still acceptable diff --git a/CHANGELOG.md b/CHANGELOG.md index 2c938e0..96e33ef 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,10 @@ Earlier entries pre-date this convention and only carry their version's compare ## [Unreleased] +### Added + +- Report `savedPreference`, `transportConfigured`, and `captureActive` in telemetry status output. `enabled` continues to reflect runtime opt-outs ([#76](https://github.com/AgoraIO/cli/pull/76)). + ### Changed - Rename the `project show --json` token debug status to `signalingTokenDebugEnabled` and remove the misleading token capability warning from `project doctor`. Update consumers of the old `tokenEnabled` result field. diff --git a/docs/automation.md b/docs/automation.md index 4a86a01..fd1ea6d 100644 --- a/docs/automation.md +++ b/docs/automation.md @@ -1183,6 +1183,20 @@ Safe branch fields by command shape: - Show/create/update: `projectId`, `feature`, `configId`, `enabled`, `eventIds`, `urlRegion` - Delete: `projectId`, `feature`, `configId`, `deleted` +### `telemetry status`, `telemetry enable`, `telemetry disable` + +The `telemetry` result reports these fields: + +- `action` identifies the operation as `status`, `enable`, or `disable`. +- `configPath` is the local configuration file path. +- `doNotTrack` indicates whether `DO_NOT_TRACK` is set to a non-empty value. +- `savedPreference` is the configured telemetry preference. +- `enabled` combines the preference and runtime opt-outs. +- `transportConfigured` indicates whether a valid collector URL is configured. +- `captureActive` requires both `enabled` and `transportConfigured`. + +The `agora.telemetry.status` MCP tool returns the same fields. + ### `config path` Example: diff --git a/docs/telemetry.md b/docs/telemetry.md index c1604c8..9e62fcd 100644 --- a/docs/telemetry.md +++ b/docs/telemetry.md @@ -4,80 +4,93 @@ title: Telemetry # Telemetry -Agora CLI telemetry is limited to operational diagnostics such as command -failures and local log metadata. It **never** includes OAuth tokens, app -certificates, dotenv secrets, or project env values. Field redaction is -enforced by `redactTelemetryFields` in -[`internal/cli/telemetry.go`](https://github.com/AgoraIO/cli/blob/main/internal/cli/telemetry.go), -which matches the `token | secret | password | api[_-]?key | authorization` -key pattern (case-insensitive) and replaces the value with the literal -`[REDACTED]`. - -> **Status (current release):** the on/off contract below is fully -> wired. The transport (Sentry SDK) is not yet linked into the binary, -> so all telemetry calls are no-ops at runtime. The next release will -> wire Sentry; the surface and field schema will not change. +Agora CLI can report Recipes usage, init stages/results and project creation +results to the CLI BFF, which forwards allowlisted events to PostHog. Capture is +enabled by default when a valid collector URL is configured, unless the user +opts out. The embedded collector URL is currently empty; deployment and release +configuration are required before production capture is active. + +Events contain a random local installation ID, a per-operation ID, CLI version, +OS/architecture, coarse AI-tool categories, public recipe/template IDs, timings +and structured results. Project/init events can include validated Agora App IDs. +An installation profile can be created in PostHog. Agora App IDs can be +associated with Agora projects and companies. OAuth tokens, App Certificates, project names, source code, conversation +content, local paths and raw errors are not included. + +Recipe init attempts are labeled as Recipe usage even if the catalog lookup +fails. Only attempts with a confirmed public catalog entry include a Recipe ID. +When reporting per-Recipe results, show unconfirmed attempts separately. +An existing target directory is reported as a local validation failure. + +## Delivery + +Each instrumented shell command collects its events in memory and flushes them +when the operation finishes. MCP flushes after each instrumented tool call, +independently of other calls and without waiting for the MCP server to exit. + +The CLI passes one JSON batch through stdin to a detached sender subprocess. +The sender makes one HTTP request with a ten-second timeout. The business +command waits only for a local handoff of at most 100 ms, not for the network +response. Telemetry failures do not change business output or exit codes. + +The complete request is limited to 64 KiB. There is no separate event-count or +per-event size cap. If an operation exceeds the request limit, its entire batch +is dropped. There is no disk queue or retry. A crash or forced termination before +handoff can lose all events for that operation; long-running operations are not +visible in telemetry until they finish. Successful delivery is best effort and +does not prove that PostHog has made the events available for queries. + +The sender honors `HTTP_PROXY`, `HTTPS_PROXY`, `NO_PROXY` and their lowercase +forms, as the business HTTP client does. It also preserves `SSL_CERT_FILE` and +`SSL_CERT_DIR` for custom certificate authorities. Other parent environment +variables are not inherited. Business authorization headers are not attached to +telemetry requests, and redirects are not followed. ## Inspect or change the setting -Telemetry is enabled by default in the local config. - -```bash -agora telemetry status -agora telemetry disable -agora telemetry enable -``` - -For scripts, prefer JSON: - ```bash +agora telemetry status --json agora telemetry disable --json +agora telemetry enable --json ``` -## Opt-out signals +`savedPreference` reports the configured preference. `enabled` also accounts +for runtime opt-outs. `transportConfigured` reports whether a valid collector +URL is configured. `captureActive` requires both `enabled` and +`transportConfigured`. It tracks whether capture can start. -The CLI honors **all** of the following — any one of them disables -telemetry for the current process: +Shell commands print a first-use disclosure to stderr unless quiet mode +suppresses it. MCP includes the disclosure in its initialization instructions +when a collector is configured. MCP hosts decide how to present instructions. +The disclosure provides notice. The first instrumented call can collect events +when capture is active. -| Signal | Notes | -|--------|-------| -| `DO_NOT_TRACK=` | Standard cross-tool convention. Also suppresses local file logs for that process. | -| `AGORA_SENTRY_ENABLED=0` | Hard env override. Wins over the config file. | -| `agora telemetry disable` | Persists `telemetryEnabled: false` to the config. | -| `agora config update --telemetry-enabled=false` | Equivalent to `agora telemetry disable`. | +Any of these signals disables capture: -```bash -DO_NOT_TRACK=1 agora project list --json -AGORA_SENTRY_ENABLED=0 agora init my-app --template nextjs --json -``` +| Signal | Effect | +|--------|--------| +| `DO_NOT_TRACK=` | Runtime opt-out. Also suppresses local file logs. | +| `AGORA_TELEMETRY_ENABLED=0` | Runtime opt-out for usage capture. | +| `AGORA_SENTRY_ENABLED=0` | Runtime opt-out honored by usage capture. | +| `agora telemetry disable` | Saves `telemetryEnabled: false`. | +| `agora config update --telemetry-enabled=false` | Saves the same preference. | -## Field schema +Shell commands use their startup preference. A running MCP server rereads the +saved preference when each tool call starts. A preference change does not alter +an operation that has already started. -The wire-up plan documents the **exact** field set the Sentry-backed -sink will send. Until then the table below is forward-looking; treat it -as the specification, not the production behavior: +## Collector configuration -| Field | Type | Example | Notes | -|-----------------|--------|------------------------------------|-------| -| `command` | string | `"project create"` | Stable label from `agora introspect --json`. | -| `exitCode` | int | `1` | Process exit code at failure. | -| `commitSha` | string | `"abc1234"` | Build-time injected. | -| `os` | string | `"darwin/arm64"` | Runtime, not host-specific. | -| `installMethod` | string | `"installer"` / `"npm"` / `"brew"` | From the install provenance receipt. | -| `agentLabel` | string | `"cursor"` | From `agent_infer.go`. | +`AGORA_TELEMETRY_URL` overrides the release-embedded collector URL. Only HTTPS +URLs, or HTTP URLs on loopback for local verification, are accepted. URLs with +credentials, query parameters or fragments are rejected. -Explicitly **never** sent: +The existing operational-diagnostics sink is separate from these usage events; +its Sentry transport remains a placeholder. Usage capture does not require an +OAuth login or a client-side PostHog API key. -- OAuth tokens or session refresh tokens. -- Agora App Certificate values. -- Project names or App IDs (use opaque hashes if needed in the future). -- Local file paths beyond the rotating log file path basename. - -## Where the config lives +The configuration location is available with: ```bash agora config path ``` - -The same directory holds the rotating log file (`agora-cli.log`) and -the project list cache used by shell completion. diff --git a/go.mod b/go.mod index 9587d1d..26adfb8 100644 --- a/go.mod +++ b/go.mod @@ -5,10 +5,8 @@ go 1.26.6 require ( github.com/spf13/cobra v1.10.2 github.com/spf13/pflag v1.0.10 + golang.org/x/sys v0.47.0 golang.org/x/term v0.45.0 ) -require ( - github.com/inconshreveable/mousetrap v1.1.0 // indirect - golang.org/x/sys v0.47.0 // indirect -) +require github.com/inconshreveable/mousetrap v1.1.0 // indirect diff --git a/internal/cli/agent_infer.go b/internal/cli/agent_infer.go index bffd71d..7f9e853 100644 --- a/internal/cli/agent_infer.go +++ b/internal/cli/agent_infer.go @@ -12,14 +12,16 @@ func agentLabelFromOSEnv(env map[string]string) string { switch { case nonEmptyEnv(env, "CURSOR_AGENT"): return "cursor" - case nonEmptyEnv(env, "CLAUDE_CODE"): + case nonEmptyEnv(env, "CLAUDE_CODE") || nonEmptyEnv(env, "CLAUDECODE"): return "claude-code" case hasEnvPrefix(env, "CLINE_"): return "cline" case hasEnvPrefix(env, "WINDSURF_"): return "windsurf" - case hasEnvPrefix(env, "OPENAI_CODEX_"): + case nonEmptyEnv(env, "CODEX_THREAD_ID") || hasEnvPrefix(env, "OPENAI_CODEX_"): return "codex" + case nonEmptyEnv(env, "KIRO_SESSION_ID"): + return "kiro" case hasEnvPrefix(env, "AIDER_"): return "aider" default: diff --git a/internal/cli/agent_infer_test.go b/internal/cli/agent_infer_test.go index 98cbdc4..d52b3f0 100644 --- a/internal/cli/agent_infer_test.go +++ b/internal/cli/agent_infer_test.go @@ -13,11 +13,15 @@ func TestAgentLabelFromOSEnv(t *testing.T) { }{ {name: "explicit wins", env: map[string]string{"AGORA_AGENT": "custom", "CURSOR_AGENT": "1"}, want: "custom"}, {name: "disabled", env: map[string]string{"AGORA_AGENT_DISABLE_INFER": "1", "CURSOR_AGENT": "1"}, want: ""}, + {name: "explicit wins over codex", env: map[string]string{"AGORA_AGENT": "custom", "CODEX_THREAD_ID": "thread-123"}, want: "custom"}, + {name: "disabled codex", env: map[string]string{"AGORA_AGENT_DISABLE_INFER": "1", "CODEX_THREAD_ID": "thread-123"}, want: ""}, {name: "cursor", env: map[string]string{"CURSOR_AGENT": "1"}, want: "cursor"}, {name: "claude code", env: map[string]string{"CLAUDE_CODE": "1"}, want: "claude-code"}, {name: "cline", env: map[string]string{"CLINE_SESSION": "abc"}, want: "cline"}, {name: "windsurf", env: map[string]string{"WINDSURF_SESSION": "abc"}, want: "windsurf"}, - {name: "codex", env: map[string]string{"OPENAI_CODEX_SESSION": "abc"}, want: "codex"}, + {name: "codex thread", env: map[string]string{"CODEX_THREAD_ID": "thread-123"}, want: "codex"}, + {name: "codex legacy", env: map[string]string{"OPENAI_CODEX_SESSION": "abc"}, want: "codex"}, + {name: "codex empty thread", env: map[string]string{"CODEX_THREAD_ID": ""}, want: ""}, {name: "aider", env: map[string]string{"AIDER_AUTO_COMMITS": "false"}, want: "aider"}, {name: "empty", env: map[string]string{}, want: ""}, } @@ -37,6 +41,13 @@ func TestAgoraUserAgentInfersCursorAgent(t *testing.T) { } } +func TestAgoraUserAgentInfersCodexThread(t *testing.T) { + got := agoraUserAgent(map[string]string{"CODEX_THREAD_ID": "thread-123"}) + if got != "agora-cli/"+version+" agent/codex" { + t.Fatalf("unexpected user agent: %q", got) + } +} + // TestDecideShouldPromptForLoginYesFlagDoesNotBypassGuards is the // regression test for the bug where `--yes` / AGORA_NO_INPUT used to // short-circuit the JSON/CI/non-TTY guards in shouldPromptForLogin and diff --git a/internal/cli/analytics.go b/internal/cli/analytics.go new file mode 100644 index 0000000..dc625ad --- /dev/null +++ b/internal/cli/analytics.go @@ -0,0 +1,389 @@ +package cli + +import ( + "context" + "crypto/rand" + "encoding/hex" + "encoding/json" + "errors" + "maps" + "net/url" + "os" + "path/filepath" + "regexp" + "runtime" + "strings" + "time" + + "github.com/spf13/cobra" +) + +// Empty until an approved collector is deployed. Release builds may set this +// with -ldflags; local verification uses AGORA_TELEMETRY_URL. +var analyticsEndpoint = "" + +const analyticsSendTimeout = 10 * time.Second + +var analyticsIDPattern = regexp.MustCompile(`^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$`) +var analyticsSlugPattern = regexp.MustCompile(`^[a-z0-9]+(?:-[a-z0-9]+)*$`) +var analyticsVersionPattern = regexp.MustCompile(`^[A-Za-z0-9.+_-]{0,64}$`) +var analyticsCodePattern = regexp.MustCompile(`^[A-Z][A-Z0-9_]{0,63}$`) + +type analyticsEvent struct { + Event string `json:"event"` + EventID string `json:"event_id"` + OperationID string `json:"operation_id"` + DistinctID string `json:"distinct_id"` + Timestamp time.Time `json:"timestamp"` + Properties map[string]any `json:"properties"` +} + +type analyticsOperation struct { + command string + id string + distinctID string + properties map[string]any + started time.Time + initStarted *analyticsEvent + stage string + stageStarted time.Time + events []json.RawMessage + batchBytes int + endpoint string +} + +type analyticsContextKey struct{} + +func analyticsUUID() string { + var b [16]byte + if _, err := rand.Read(b[:]); err != nil { + return "" + } + b[6] = (b[6] & 15) | 64 + b[8] = (b[8] & 63) | 128 + h := hex.EncodeToString(b[:]) + return h[:8] + "-" + h[8:12] + "-" + h[12:16] + "-" + h[16:20] + "-" + h[20:] +} + +func (a *App) analyticsEnabled() bool { + if a.analyticsOptedOut() { + return false + } + return a.cfg.TelemetryEnabled +} + +func (a *App) analyticsOptedOut() bool { + if a == nil || strings.TrimSpace(a.env["DO_NOT_TRACK"]) != "" || a.env["AGORA_TELEMETRY_ENABLED"] == "0" { + return true + } + sentryOverride := a.env["AGORA_SENTRY_ENABLED"] + if a.cfgState.ConfigFilePath != "" { + // applyConfigToEnv also writes this key. Only an explicit OS override + // should mask a preference changed since this MCP process started. + sentryOverride = a.osEnv["AGORA_SENTRY_ENABLED"] + } + return sentryOverride == "0" +} + +func (a *App) currentTelemetryPreference() bool { + cfg, valid := a.currentTelemetryConfig() + return valid && cfg.TelemetryEnabled +} + +func (a *App) currentTelemetryConfig() (appConfig, bool) { + path, err := resolveConfigFilePath(a.env) + if err != nil { + return appConfig{}, false + } + data, err := os.ReadFile(path) + if errors.Is(err, os.ErrNotExist) && a.cfgState.ConfigFilePath == "" { + return a.cfg, true // Apps constructed without a config store. + } + if err != nil { + return appConfig{}, false + } + var fields map[string]json.RawMessage + if json.Unmarshal(data, &fields) != nil || fields == nil { + return appConfig{}, false + } + if enabled, ok := fields["telemetryEnabled"]; ok && string(enabled) != "true" && string(enabled) != "false" { + return appConfig{}, false + } + config := defaultConfig() + if json.Unmarshal(data, &config) != nil { + return appConfig{}, false + } + return config, true +} + +func (a *App) analyticsURL() string { + endpoint := strings.TrimSpace(a.env["AGORA_TELEMETRY_URL"]) + if endpoint == "" { + endpoint = analyticsEndpoint + } + u, err := url.Parse(endpoint) + if err != nil || u.Host == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" { + return "" + } + if u.Scheme != "https" && !(u.Scheme == "http" && (u.Hostname() == "127.0.0.1" || u.Hostname() == "localhost" || u.Hostname() == "::1")) { + return "" + } + return endpoint +} + +func (a *App) analyticsIdentity() string { + dir, err := resolveAgoraDirectory(a.env) + if err != nil { + return "" + } + path := filepath.Join(dir, "analytics-id") + if b, err := os.ReadFile(path); err == nil { + id := strings.TrimSpace(string(b)) + if len(id) == 36 && analyticsIDPattern.MatchString(id) { + return "cli:" + id + } + return "" + } + if err := os.MkdirAll(dir, 0o700); err != nil { + return "" + } + id := analyticsUUID() + if id == "" { + return "" + } + f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600) + if err != nil { + if b, readErr := os.ReadFile(path); readErr == nil { + other := strings.TrimSpace(string(b)) + if len(other) == 36 && analyticsIDPattern.MatchString(other) { + return "cli:" + other + } + } + return "" + } + _, writeErr := f.WriteString(id) + closeErr := f.Close() + if writeErr != nil || closeErr != nil { + return "" + } + return "cli:" + id +} + +func (a *App) beginAnalytics(command, channel string) *analyticsOperation { + endpoint := a.analyticsURL() + enabled := a.analyticsEnabled() + if channel == "mcp" { + enabled = a.currentTelemetryPreference() && !a.analyticsOptedOut() + } + if !enabled || endpoint == "" { + return nil + } + props := map[string]any{"command": command, "os": runtime.GOOS, "arch": runtime.GOARCH, "invocation_channel": channel} + version, _ := versionInfo()["version"].(string) + if !analyticsVersionPattern.MatchString(version) { + version = "custom" + } + props["cli_version"] = version + family, surface, source := analyticsAgent(a.osEnv) + props["agent_family"], props["agent_surface"], props["agent_detection_source"] = family, surface, source + id := a.analyticsIdentity() + if id == "" { + return nil + } + op := &analyticsOperation{command: command, id: analyticsUUID(), distinctID: id, properties: props, started: time.Now(), endpoint: endpoint} + if command == "init" { + event := op.newEvent("cli_init_started", nil) + op.initStarted = &event + op.beginStage("validate") + } + return op +} + +func analyticsAgent(env map[string]string) (family, surface, source string) { + surface, source = "unknown", "none" + label := agentLabelFromOSEnv(env) + family = "unknown" + if label == "" { + return + } + source = "environment" + if strings.TrimSpace(env["AGORA_AGENT"]) != "" { + source = "explicit" + } + switch label { + case "codex", "claude-code", "kiro", "cursor", "cline", "windsurf", "aider": + family = label + default: + family = "custom" + } + if family == "claude-code" { + switch env["CLAUDE_CODE_ENTRYPOINT"] { + case "cli": + surface = "cli" + case "claude-desktop": + surface = "desktop" + } + } + if family == "codex" && env["CODEX_INTERNAL_ORIGINATOR_OVERRIDE"] == "Codex Desktop" { + surface = "desktop" + } + if family == "kiro" { + if env["AWS_SDK_UA_APP_ID"] == "kiro-ide" { + surface = "desktop" + } else if env["KIRO_CLI_ACP_CLIENT_NAME"] == "kiro-tui" { + surface = "cli" + } + } + return +} + +func (op *analyticsOperation) emit(name string, fields map[string]any) { + if op == nil { + return + } + op.submit(op.newEvent(name, fields)) +} + +func (op *analyticsOperation) newEvent(name string, fields map[string]any) analyticsEvent { + props := maps.Clone(op.properties) + maps.Copy(props, fields) + return analyticsEvent{Event: name, EventID: analyticsUUID(), OperationID: op.id, DistinctID: op.distinctID, Timestamp: time.Now().UTC(), Properties: props} +} + +func (op *analyticsOperation) beginStage(stage string) { + if op == nil || op.command != "init" { + return + } + if op.stage != "" { + op.completeStage(nil) + } + op.stage, op.stageStarted = stage, time.Now() +} + +func analyticsOutcome(err error) (string, string) { + if err == nil { + return "success", "" + } + var ce *cliError + code := "CLI_ERROR" + if errors.As(err, &ce) && analyticsCodePattern.MatchString(ce.Code) { + code = ce.Code + } + if errors.Is(err, context.Canceled) || code == "INIT_ABORTED" { + return "cancelled", code + } + return "failure", code +} + +func (op *analyticsOperation) completeStage(err error) { + if op == nil || op.stage == "" { + return + } + outcome, code := analyticsOutcome(err) + op.emit("cli_init_stage_completed", map[string]any{"stage": op.stage, "outcome": outcome, "error_code": code, "duration_ms": time.Since(op.stageStarted).Milliseconds()}) + op.stage = "" +} + +func (op *analyticsOperation) finish(err error) { + if op == nil { + return + } + failedStage := "" + if err != nil { + failedStage = op.stage + } + op.completeStage(err) + outcome, code := analyticsOutcome(err) + fields := map[string]any{"outcome": outcome, "error_code": code, "duration_ms": time.Since(op.started).Milliseconds(), "exit_code": 0} + if err != nil { + fields["exit_code"] = exitCodeForError(err) + } + event := "cli_" + strings.ReplaceAll(op.command, " ", "_") + "_completed" + if op.command == "init" && failedStage != "" { + fields["failed_stage"] = failedStage + } + if op.command != "project create" { + op.emit(event, fields) + } + op.flush() +} + +func analyticsFor(cmd *cobra.Command) *analyticsOperation { + op, _ := cmd.Context().Value(analyticsContextKey{}).(*analyticsOperation) + return op +} + +func (a *App) instrumentAnalytics(cmd *cobra.Command, command string) { + run := cmd.RunE + cmd.RunE = func(cmd *cobra.Command, args []string) (err error) { + if dry, _ := cmd.Flags().GetBool("dry-run"); dry { + return run(cmd, args) + } + a.maybeShowTelemetryNotice(cmd) + op := a.beginAnalytics(command, "shell") + if command == "init" { + recipe, _ := cmd.Flags().GetString("recipe") + template, _ := cmd.Flags().GetString("template") + op.setInitSourceType(recipe, template) + } + ctx := cmd.Context() + cmd.SetContext(context.WithValue(ctx, analyticsContextKey{}, op)) + defer func() { op.finish(err); cmd.SetContext(ctx) }() + return run(cmd, args) + } +} + +func firstAnalytics(ops []*analyticsOperation) *analyticsOperation { + if len(ops) > 0 { + return ops[0] + } + return nil +} + +func (op *analyticsOperation) setInitSourceType(recipe, template string) { + if op == nil { + return + } + recipe, template = strings.TrimSpace(recipe), strings.TrimSpace(template) + switch { + case recipe != "" && template == "": + op.properties["source_type"] = "recipe" + case template != "" && recipe == "": + op.properties["source_type"] = "quickstart" + } +} + +func (op *analyticsOperation) source(kind, id string) { + if op == nil || len(id) > 100 || !analyticsSlugPattern.MatchString(id) { + return + } + op.properties["source_type"], op.properties["source_id"] = kind, id + if kind == "recipe" { + op.properties["recipe_id"] = id + } +} + +var analyticsAppIDPattern = regexp.MustCompile(`^[0-9a-fA-F]{32}$`) +var analyticsPlatformPattern = regexp.MustCompile(`^[a-z0-9]{1,20}$`) + +func (op *analyticsOperation) setAppID(id string) { + if op == nil || !analyticsAppIDPattern.MatchString(id) || op.properties["app_id"] != nil { + return + } + op.properties["app_id"] = id +} + +func (op *analyticsOperation) projectCreated(id string, started time.Time, err error) { + if op == nil { + return + } + if err == nil { + op.setAppID(id) + } + outcome, code := analyticsOutcome(err) + exit := 0 + if err != nil { + exit = exitCodeForError(err) + } + op.emit("cli_project_create_completed", map[string]any{"outcome": outcome, "error_code": code, "duration_ms": time.Since(started).Milliseconds(), "exit_code": exit}) +} diff --git a/internal/cli/analytics_acl_windows_test.go b/internal/cli/analytics_acl_windows_test.go new file mode 100644 index 0000000..f41a2ae --- /dev/null +++ b/internal/cli/analytics_acl_windows_test.go @@ -0,0 +1,64 @@ +package cli + +import ( + "path/filepath" + "strings" + "testing" + "unsafe" + + "golang.org/x/sys/windows" +) + +func TestAnalyticsInstallationIDWindowsACL(t *testing.T) { + a := analyticsTestApp(t, "") + if a.analyticsIdentity() == "" { + t.Fatal("could not create installation ID") + } + path := filepath.Join(a.env["AGORA_HOME"], "analytics-id") + sd, err := windows.GetNamedSecurityInfo(path, windows.SE_FILE_OBJECT, windows.OWNER_SECURITY_INFORMATION|windows.DACL_SECURITY_INFORMATION) + if err != nil { + t.Fatal(err) + } + owner, _, err := sd.Owner() + if err != nil { + t.Fatal(err) + } + dacl, _, err := sd.DACL() + if err != nil || dacl == nil { + t.Fatalf("installation ID must have a DACL, got %v", err) + } + var computerName [256]uint16 + size := uint32(len(computerName)) + if err := windows.GetComputerName(&computerName[0], &size); err != nil { + t.Fatal(err) + } + localDomain := windows.UTF16ToString(computerName[:size]) + for i := range uint32(dacl.AceCount) { + var ace *windows.ACCESS_ALLOWED_ACE + if err := windows.GetAce(dacl, i, &ace); err != nil { + t.Fatal(err) + } + if ace.Header.AceFlags&windows.INHERIT_ONLY_ACE != 0 || ace.Header.AceType == windows.ACCESS_DENIED_ACE_TYPE { + continue + } + if ace.Header.AceType != windows.ACCESS_ALLOWED_ACE_TYPE { + t.Fatalf("unexpected installation ID ACL entry type %d", ace.Header.AceType) + } + if ace.Mask&(windows.FILE_READ_DATA|windows.GENERIC_READ|windows.GENERIC_ALL) == 0 { + continue + } + principal := (*windows.SID)(unsafe.Pointer(&ace.SidStart)) + if principal.Equals(owner) || principal.IsWellKnown(windows.WinLocalSystemSid) || principal.IsWellKnown(windows.WinBuiltinAdministratorsSid) { + continue + } + // The local built-in Administrator has a machine-specific SID with RID 500, + // separate from the well-known Administrators group SID. + if principal.SubAuthorityCount() == 5 && principal.SubAuthority(4) == 500 { + _, domain, accountType, err := principal.LookupAccount("") + if err == nil && accountType == windows.SidTypeUser && strings.EqualFold(domain, localDomain) { + continue + } + } + t.Errorf("installation ID is readable by unexpected principal %s", principal) + } +} diff --git a/internal/cli/analytics_final_test.go b/internal/cli/analytics_final_test.go new file mode 100644 index 0000000..051b0b4 --- /dev/null +++ b/internal/cli/analytics_final_test.go @@ -0,0 +1,416 @@ +package cli + +import ( + "bytes" + "context" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "strings" + "sync/atomic" + "testing" + "time" +) + +const testTelemetryAppID = "0123456789abcdef0123456789abcdef" + +func TestAnalyticsCreationSurvivesLaterFailure(t *testing.T) { + for _, channel := range []string{"shell", "mcp"} { + for _, source := range []string{"project create", "quickstart", "recipe"} { + for _, failure := range []string{"features", "query"} { + t.Run(channel+"/"+source+"/"+failure, func(t *testing.T) { + collector, read := analyticsRecorder(t) + a := analyticsTestApp(t, collector.URL) + var creates atomic.Int32 + backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == "POST" && r.URL.Path == "/api/cli/v1/projects" { + creates.Add(1) + time.Sleep(25 * time.Millisecond) + _ = json.NewEncoder(w).Encode(projectDetail{AppID: testTelemetryAppID, ProjectID: "prj_created", Name: "private-project"}) + return + } + if failure == "features" { + time.Sleep(120 * time.Millisecond) + } + w.WriteHeader(http.StatusServiceUnavailable) + _, _ = w.Write([]byte(`{"message":"private failure"}`)) + })) + defer backend.Close() + a.env["AGORA_API_BASE_URL"] = backend.URL + a.osEnv["AGORA_API_BASE_URL"] = backend.URL + if err := saveSession(a.env, session{AccessToken: "secret", TokenType: "Bearer", ExpiresAt: time.Now().Add(time.Hour).Format(time.RFC3339)}); err != nil { + t.Fatal(err) + } + command := "init" + if source == "project create" { + command = source + } + op := a.beginAnalytics(command, channel) + features := []string{"rtc"} + if failure == "features" { + features = []string{"rtm"} + } + var err error + if command == "project create" { + _, err = a.projectCreate("private-project", "", features, "", "", op) + } else { + target := filepath.Join(t.TempDir(), "demo") + if source == "quickstart" { + template, selectErr := selectQuickstartDefinition("nextjs", "video-call") + if selectErr != nil { + t.Fatal(selectErr) + } + _, err = a.initProject("private-project", target, template, "", features, "", true, false, io.Discard, strings.NewReader(""), nil, op) + } else { + recipe := recipeDetail{recipeSummary: recipeSummary{Slug: "test-source"}, CLI: &recipeCLIConfig{ProjectType: "python", Env: recipeCLIEnv{ExamplePath: ".env.example", TargetPath: ".env", AppIDKey: "AGORA_APP_ID", AppCertificateKey: "AGORA_APP_CERTIFICATE"}}} + _, err = a.initRecipeProject("private-project", target, recipe, "", features, "", true, false, io.Discard, strings.NewReader(""), nil, op) + } + } + if command == "init" && err == nil { + t.Fatal("fixture must fail after creation") + } + op.finish(err) + events := waitAnalyticsEvents(t, read, 1) + var creation *analyticsEvent + for i := range events { + e := &events[i] + if e.Event == "cli_project_create_completed" { + if creation != nil { + t.Fatal("duplicate creation") + } + creation = e + } + if e.Event == "cli_init_started" && e.Properties["app_id"] != nil { + t.Fatal("backfilled early event") + } + if e.Event == "cli_init_completed" && (e.Properties["outcome"] != "failure" || e.Properties["app_id"] != testTelemetryAppID) { + t.Fatalf("lost outer failure/App ID: %+v", e) + } + } + if creates.Load() != 1 || creation == nil || creation.Properties["outcome"] != "success" || creation.Properties["exit_code"] != float64(0) || creation.Properties["app_id"] != testTelemetryAppID { + t.Fatalf("wrong creation %+v", events) + } + duration := creation.Properties["duration_ms"].(float64) + if duration < 20 || duration > 115 { + t.Fatalf("creation timing includes later feature work: %v", duration) + } + }) + } + } + } +} + +func TestAnalyticsCreationAuthFailureAndInvalidAppID(t *testing.T) { + collector, read := analyticsRecorder(t) + a := analyticsTestApp(t, collector.URL) + a.env["AGORA_OUTPUT"] = "json" + op := a.beginAnalytics("project create", "mcp") + if _, err := a.createProject("private", "", op); err == nil { + t.Fatal("expected auth failure") + } + op.finish(nil) + events := waitAnalyticsEvents(t, read, 1) + if len(events) != 1 || events[0].Properties["outcome"] != "failure" || events[0].Properties["app_id"] != nil { + t.Fatal(events) + } + for _, id := range []string{"private name", "app_0001", "", "secret-token"} { + op.setAppID(id) + } + if op.properties["app_id"] != nil { + t.Fatal("accepted free text app ID") + } +} + +func TestAnalyticsBatchIsDeferredUntilFinish(t *testing.T) { + var calls atomic.Int32 + received := make(chan []analyticsEvent, 1) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var batch analyticsBatch + if err := json.NewDecoder(r.Body).Decode(&batch); err != nil { + t.Error(err) + return + } + calls.Add(1) + received <- batch.Events + // All lifecycle events arrive together, even with a slow acknowledgement. + time.Sleep(600 * time.Millisecond) + w.WriteHeader(http.StatusAccepted) + })) + defer server.Close() + a := analyticsTestApp(t, server.URL) + op := a.beginAnalytics("init", "shell") + for _, stage := range []string{"source_resolve", "project_resolve", "clone", "env_write", "binding_write", "context_write"} { + op.beginStage(stage) + } + if calls.Load() != 0 { + t.Fatal("sent before operation finished") + } + started := time.Now() + op.finish(nil) + if time.Since(started) > 500*time.Millisecond { + t.Fatal("finish waited for network") + } + select { + case events := <-received: + if len(events) != 9 || events[0].Event != "cli_init_started" || events[len(events)-1].Event != "cli_init_completed" { + t.Fatalf("missing batch lifecycle: %+v", events) + } + case <-time.After(2 * time.Second): + t.Fatal("batch missing") + } + if calls.Load() != 1 { + t.Fatal("operation sent multiple requests") + } +} + +func TestAnalyticsBatchHandoffAndSizeBound(t *testing.T) { + reader, writer := io.Pipe() + defer func() { _ = reader.Close() }() + started := time.Now() + handoffAnalyticsBatch(writer, []byte(`{"events":[]}`)) + if time.Since(started) > 500*time.Millisecond { + t.Fatal("blocked on non-reading pipe") + } + if _, err := writer.Write([]byte("x")); err == nil { + t.Fatal("timed-out pipe remained open") + } + + server, read := analyticsRecorder(t) + a := analyticsTestApp(t, server.URL) + op := a.beginAnalytics("recipes list", "shell") + for range 1000 { + op.emit("cli_recipes_list_completed", nil) + } + if op.batchBytes <= analyticsRequestLimit || len(op.events) != 0 { + t.Fatal("oversized batch was retained") + } + op.finish(nil) + if len(read()) != 0 { + t.Fatal("sent a partial oversized operation") + } +} + +func TestAnalyticsBatchRejectsMalformedOrPrivateInput(t *testing.T) { + server, read := analyticsRecorder(t) + a := analyticsTestApp(t, server.URL) + op := a.beginAnalytics("recipes list", "shell") + event := analyticsEvent{Event: "cli_recipes_list_completed", EventID: analyticsUUID(), OperationID: op.id, DistinctID: op.distinctID, Timestamp: time.Now().UTC(), Properties: op.properties} + body, _ := json.Marshal(analyticsBatch{Events: []analyticsEvent{event}}) + private := bytes.Replace(body, []byte(`"properties":{`), []byte(`"properties":{"token":"private",`), 1) + for _, input := range [][]byte{private, append(bytes.Clone(body), []byte(` {}`)...), []byte(`{"events":[]}`), []byte(`{"events":null}`), []byte(`{"unknown":true,"events":[]}`), []byte(strings.Repeat(" ", analyticsRequestLimit+1)), body[:len(body)-1]} { + sendAnalyticsBatch(bytes.NewReader(input), server.URL) + } + if len(read()) != 0 { + t.Fatal("invalid batch was sent") + } + events := make([]analyticsEvent, 21) + for i := range events { + events[i] = event + events[i].EventID = analyticsUUID() + } + body, _ = json.Marshal(analyticsBatch{Events: events}) + sendAnalyticsBatch(bytes.NewReader(append([]byte(strings.Repeat(" ", 5000)), body...)), server.URL) + if len(read()) != 21 { + t.Fatalf("valid batch was not sent: %d", len(read())) + } +} + +func TestAnalyticsMCPBatchesDoNotDropWhileOtherSendersWait(t *testing.T) { + received := make(chan string, 3) + release := make(chan struct{}) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var batch analyticsBatch + if err := json.NewDecoder(r.Body).Decode(&batch); err != nil { + t.Error(err) + return + } + if len(batch.Events) != 3 { + t.Errorf("unexpected lifecycle length: %d", len(batch.Events)) + } + received <- batch.Events[0].OperationID + <-release + w.WriteHeader(http.StatusAccepted) + })) + defer server.Close() + defer close(release) + a := analyticsTestApp(t, server.URL) + for range 3 { + if _, err := a.callMCPTool("agora.init", map[string]any{}, nil); err == nil { + t.Fatal("missing name must fail") + } + } + ids := map[string]bool{} + for range 3 { + select { + case id := <-received: + ids[id] = true + case <-time.After(2 * time.Second): + t.Fatal("MCP batch dropped while previous senders were waiting") + } + } + if len(ids) != 3 { + t.Fatal("MCP operation identities were shared") + } +} + +func TestAnalyticsSenderSurvivesParentExit(t *testing.T) { + received := make(chan analyticsEvent, 4) + allowResponse := make(chan struct{}, 1) + var calls atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var body struct { + Events []analyticsEvent `json:"events"` + } + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + t.Error(err) + return + } + for _, e := range body.Events { + received <- e + } + if calls.Add(1) == 1 { + <-allowResponse + } + w.WriteHeader(http.StatusAccepted) + })) + defer server.Close() + defer func() { + select { + case allowResponse <- struct{}{}: + default: + } + }() + home := t.TempDir() + executable, err := os.Executable() + if err != nil { + t.Fatal(err) + } + cmd := exec.Command(executable) + cmd.Env = append(os.Environ(), "GO_WANT_CLI_HELPER_PROCESS=1", `GO_CLI_HELPER_ARGS_JSON=["init","local-only","--template","invalid","--json"]`, "AGORA_HOME="+home, "AGORA_TELEMETRY_URL="+server.URL, "AGORA_SENTRY_ENABLED=1", "AGORA_TELEMETRY_ENABLED=1", "DO_NOT_TRACK=") + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + done := make(chan error, 1) + go func() { _, err := cmd.CombinedOutput(); done <- err }() + select { + case <-done: + case <-ctx.Done(): + if cmd.Process != nil { + _ = cmd.Process.Kill() + } + t.Fatal("child retained output handles") + } + // The parent exits while the child waits for the batch response. + allowResponse <- struct{}{} + events := make([]analyticsEvent, 0, 4) + for range 4 { + select { + case e := <-received: + events = append(events, e) + case <-time.After(2 * time.Second): + t.Fatal("child did not finish after parent exit") + } + } + if events[0].Event != "cli_init_started" || events[3].Event != "cli_init_completed" { + t.Fatalf("missing detached lifecycle: %+v", events) + } + if _, err := os.Stat(filepath.Join(home, "telemetry-notice-shown")); err != nil { + t.Fatal(err) + } +} + +func TestAnalyticsCreationTimingIncludesRefreshAndRetry(t *testing.T) { + collector, read := analyticsRecorder(t) + a := analyticsTestApp(t, collector.URL) + var requests, refreshes atomic.Int32 + backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + time.Sleep(30 * time.Millisecond) + if r.URL.Path == "/api/v0/oauth/token" { + refreshes.Add(1) + _, _ = w.Write([]byte(`{"access_token":"local","token_type":"Bearer","expires_in":3600,"refresh_token":"local","scope":"basic_info,console"}`)) + return + } + if requests.Add(1) == 1 { + w.WriteHeader(http.StatusUnauthorized) + return + } + _ = json.NewEncoder(w).Encode(projectDetail{AppID: testTelemetryAppID}) + })) + defer backend.Close() + a.osEnv["AGORA_API_BASE_URL"] = backend.URL + a.osEnv["AGORA_OAUTH_BASE_URL"] = backend.URL + if err := saveSession(a.env, session{AccessToken: "local", RefreshToken: "local", TokenType: "Bearer", ExpiresAt: time.Now().Add(-time.Hour).Format(time.RFC3339)}); err != nil { + t.Fatal(err) + } + op := a.beginAnalytics("project create", "shell") + _, err := a.createProject("local", "", op) + op.finish(err) + if err != nil { + t.Fatal(err) + } + events := waitAnalyticsEvents(t, read, 1) + if len(events) != 1 || requests.Load() != 2 || refreshes.Load() != 2 || events[0].Properties["duration_ms"].(float64) < 110 { + t.Fatalf("refresh/retry not in shared boundary: %+v requests=%d refreshes=%d", events, requests.Load(), refreshes.Load()) + } +} + +func TestAnalyticsCLIStartupAndMCPReadFailure(t *testing.T) { + for _, invalid := range []string{"{invalid", "null", `{"telemetryEnabled":null}`, `{"telemetryEnabled":"true"}`} { + t.Run(invalid, func(t *testing.T) { + server, read := analyticsRecorder(t) + a := analyticsTestApp(t, server.URL) + state, err := ensureAppConfigState(a.env) + if err != nil { + t.Fatal(err) + } + a.cfgState = state + if err := os.WriteFile(state.ConfigFilePath, []byte(invalid), 0o600); err != nil { + t.Fatal(err) + } + if op := a.beginAnalytics("recipes list", "mcp"); op != nil { + op.finish(nil) + t.Fatal("MCP used unreadable preference") + } + // Normal CLI deliberately retains the startup policy despite later edits. + op := a.beginAnalytics("recipes list", "shell") + if op == nil { + t.Fatal("CLI re-read startup preference") + } + op.finish(nil) + waitAnalyticsEvents(t, read, 1) + }) + } +} + +func TestAnalyticsBatchRequestTimeout(t *testing.T) { + received := make(chan struct{}) + release := make(chan struct{}) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = io.Copy(io.Discard, r.Body) + close(received) + <-release + })) + defer server.Close() + defer close(release) + event := analyticsEvent{Event: "cli_recipes_list_completed", EventID: analyticsUUID(), OperationID: analyticsUUID(), DistinctID: "cli:" + analyticsUUID(), Timestamp: time.Now().UTC(), Properties: map[string]any{"command": "recipes list"}} + body, _ := json.Marshal(analyticsBatch{Events: []analyticsEvent{event}}) + done := make(chan struct{}) + started := time.Now() + go func() { sendAnalyticsBatch(bytes.NewReader(body), server.URL); close(done) }() + select { + case <-received: + case <-time.After(2 * time.Second): + t.Fatal("batch request missing") + } + select { + case <-done: + case <-time.After(12 * time.Second): + t.Fatal("request exceeded ten-second timeout") + } + if time.Since(started) < 9*time.Second { + t.Fatal("request timed out before the configured ten-second budget") + } +} diff --git a/internal/cli/analytics_process_unix.go b/internal/cli/analytics_process_unix.go new file mode 100644 index 0000000..b327b0f --- /dev/null +++ b/internal/cli/analytics_process_unix.go @@ -0,0 +1,12 @@ +//go:build !windows + +package cli + +import ( + "os/exec" + "syscall" +) + +func detachAnalyticsProcess(cmd *exec.Cmd) { + cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true} +} diff --git a/internal/cli/analytics_process_windows.go b/internal/cli/analytics_process_windows.go new file mode 100644 index 0000000..66bdbd8 --- /dev/null +++ b/internal/cli/analytics_process_windows.go @@ -0,0 +1,11 @@ +package cli + +import ( + "os/exec" + "syscall" +) + +func detachAnalyticsProcess(cmd *exec.Cmd) { + // DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP. No inherited console handles. + cmd.SysProcAttr = &syscall.SysProcAttr{CreationFlags: 0x00000008 | 0x00000200, HideWindow: true} +} diff --git a/internal/cli/analytics_regression_test.go b/internal/cli/analytics_regression_test.go new file mode 100644 index 0000000..54a0d2b --- /dev/null +++ b/internal/cli/analytics_regression_test.go @@ -0,0 +1,152 @@ +package cli + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "net/url" + "os" + "strconv" + "testing" +) + +func TestAnalyticsLiveMCPPreference(t *testing.T) { + server, read := analyticsRecorder(t) + a := analyticsTestApp(t, server.URL) + state, err := ensureAppConfigState(a.env) + if err != nil { + t.Fatal(err) + } + a.cfg, a.cfgState = state.Config, state + a.applyConfigToEnv() + if _, err := a.callMCPTool("agora.init", map[string]any{}, nil); err == nil { + t.Fatal("missing name must fail") + } + before := len(waitAnalyticsEvents(t, read, 3)) + if before == 0 { + t.Fatal("expected initial capture") + } + cfg := state.Config + cfg.TelemetryEnabled = false + if err := writeSecureJSON(state.ConfigFilePath, cfg); err != nil { + t.Fatal(err) + } + if _, err := a.callMCPTool("agora.init", map[string]any{}, nil); err == nil { + t.Fatal("business validation must still fail") + } + if len(read()) != before { + t.Fatal("existing MCP continued sending after persisted opt-out") + } + status, err := a.callMCPTool("agora.telemetry.status", nil, nil) + if err != nil { + t.Fatal(err) + } + if status.(map[string]any)["captureActive"] != false { + t.Fatal("MCP status uses stale preference") + } + cfg.TelemetryEnabled = true + if err := writeSecureJSON(state.ConfigFilePath, cfg); err != nil { + t.Fatal(err) + } + op := a.beginAnalytics("recipes list", "mcp") + if op == nil { + t.Fatal("persisted re-enable did not resume capture") + } + op.finish(nil) +} + +func TestAnalyticsPolicySnapshotForRunningOperation(t *testing.T) { + server, read := analyticsRecorder(t) + a := analyticsTestApp(t, server.URL) + state, err := ensureAppConfigState(a.env) + if err != nil { + t.Fatal(err) + } + op := a.beginAnalytics("init", "mcp") + cfg := state.Config + cfg.TelemetryEnabled = false + if err := writeSecureJSON(state.ConfigFilePath, cfg); err != nil { + t.Fatal(err) + } + op.beginStage("clone") + op.finish(nil) + events := waitAnalyticsEvents(t, read, 4) + if len(events) != 4 { + t.Fatalf("running operation changed snapshot: %+v", events) + } +} + +func TestAnalyticsEOFIsFailure(t *testing.T) { + for _, err := range []error{io.EOF, io.ErrUnexpectedEOF, fmt.Errorf("API decode: %w", io.EOF), &url.Error{Op: "Get", URL: "https://example.invalid", Err: io.EOF}} { + outcome, _ := analyticsOutcome(err) + if outcome != "failure" { + t.Errorf("backend disconnect %T classified as %s", err, outcome) + } + } + for _, err := range []error{context.Canceled, fmt.Errorf("interrupted: %w", context.Canceled), &cliError{Code: "INIT_ABORTED"}} { + outcome, _ := analyticsOutcome(err) + if outcome != "cancelled" { + t.Errorf("explicit cancellation classified as %s", outcome) + } + } +} + +func TestAnalyticsBackendEOFRecordedAsFailure(t *testing.T) { + collector, read := analyticsRecorder(t) + backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Length", strconv.Itoa(1000)) + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"schemaVersion":`)) + })) + defer backend.Close() + a := analyticsTestApp(t, collector.URL) + a.env["AGORA_RECIPES_BASE_URL"] = backend.URL + _, err := a.callMCPTool("agora.recipes.list", map[string]any{}, nil) + if err == nil { + t.Fatal("truncated backend response must fail") + } + events := waitAnalyticsEvents(t, read, 1) + if len(events) != 1 { + b, _ := json.Marshal(events) + t.Fatalf("unexpected events: %s", b) + } + if events[0].Properties["outcome"] != "failure" { + t.Fatalf("backend disconnect counted as %v", events[0].Properties["outcome"]) + } +} + +func TestAnalyticsLiveConfigFailsClosedAndHonorsEnvironment(t *testing.T) { + for _, explicit := range []bool{false, true} { + t.Run(strconv.FormatBool(explicit), func(t *testing.T) { + server, _ := analyticsRecorder(t) + a := analyticsTestApp(t, server.URL) + state, err := ensureAppConfigState(a.env) + if err != nil { + t.Fatal(err) + } + a.cfgState = state + a.cfg.TelemetryEnabled = false + a.applyConfigToEnv() // Simulate starting MCP with disabled config. + if explicit { + a.osEnv["AGORA_SENTRY_ENABLED"] = "0" + } + cfg := state.Config + cfg.TelemetryEnabled = true + if err := writeSecureJSON(state.ConfigFilePath, cfg); err != nil { + t.Fatal(err) + } + if (a.currentTelemetryPreference() && !a.analyticsOptedOut()) != !explicit { + t.Fatal("persisted enable or explicit opt-out ignored") + } + if err := os.WriteFile(state.ConfigFilePath, []byte("{invalid"), 0o600); err != nil { + t.Fatal(err) + } + if a.beginAnalytics("recipes list", "mcp") != nil { + t.Fatal("unreadable preference must fail closed") + } + }) + } +} diff --git a/internal/cli/analytics_send_test.go b/internal/cli/analytics_send_test.go new file mode 100644 index 0000000..3672ce4 --- /dev/null +++ b/internal/cli/analytics_send_test.go @@ -0,0 +1,205 @@ +package cli + +import ( + "encoding/json" + "errors" + "io" + "net" + "net/http" + "net/http/httptest" + "runtime" + "strings" + "sync/atomic" + "testing" + "time" +) + +func TestAnalyticsSenderPreservesNetworkSettingsOnly(t *testing.T) { + t.Setenv("HTTPS_PROXY", "http://proxy.example:8080") + t.Setenv("NO_PROXY", "localhost,.internal") + wantSettings := []string{"HTTPS_PROXY=http://proxy.example:8080", "NO_PROXY=localhost,.internal", "SSL_CERT_FILE=/network/ca.pem"} + if runtime.GOOS != "windows" { + t.Setenv("https_proxy", "http://lowercase.example:8080") + wantSettings = append(wantSettings, "https_proxy=http://lowercase.example:8080") + } + t.Setenv("SSL_CERT_FILE", "/network/ca.pem") + t.Setenv("AGORA_ACCESS_TOKEN", "private-business-token") + t.Setenv("UNRELATED_SECRET", "private") + env := strings.Join(analyticsSenderEnv(), "\n") + for _, want := range wantSettings { + if !strings.Contains(env, want) { + t.Fatalf("missing network setting: %s", want) + } + } + if strings.Contains(env, "AGORA_ACCESS_TOKEN=") || strings.Contains(env, "UNRELATED_SECRET=") { + t.Fatal("business environment inherited by sender") + } +} + +func TestAnalyticsDetachedSenderUsesHTTPSProxy(t *testing.T) { + received := make(chan string, 1) + proxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + received <- r.Method + " " + r.Host + w.WriteHeader(http.StatusBadGateway) + })) + defer proxy.Close() + t.Setenv("https_proxy", "") + t.Setenv("HTTPS_PROXY", proxy.URL) + t.Setenv("NO_PROXY", "") + t.Setenv("no_proxy", "") + a := analyticsTestApp(t, "https://collector.example.invalid/api/telemetry/v1/events") + op := a.beginAnalytics("recipes list", "shell") + op.finish(nil) + select { + case got := <-received: + if got != "CONNECT collector.example.invalid:443" { + t.Fatalf("unexpected proxy request: %s", got) + } + case <-time.After(2 * time.Second): + t.Fatal("detached sender ignored HTTPS_PROXY") + } +} + +func TestAnalyticsFinishDoesNotWaitForResponse(t *testing.T) { + for _, flushHeaders := range []bool{false, true} { + t.Run(map[bool]string{false: "no response headers", true: "unfinished response body"}[flushHeaders], func(t *testing.T) { + release := make(chan struct{}) + received := make(chan analyticsEvent, 1) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var body struct { + Events []analyticsEvent `json:"events"` + } + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + t.Error(err) + return + } + if len(body.Events) != 1 { + t.Errorf("unexpected events: %d", len(body.Events)) + return + } + received <- body.Events[0] + if flushHeaders { + w.WriteHeader(http.StatusAccepted) + w.(http.Flusher).Flush() + } + <-release + })) + defer server.Close() + defer close(release) + a := analyticsTestApp(t, server.URL) + op := a.beginAnalytics("recipes list", "shell") + finished := make(chan struct{}) + go func() { op.finish(nil); close(finished) }() + select { + case <-finished: + case <-time.After(500 * time.Millisecond): + t.Fatal("command waited for response after writing its request") + } + select { + case event := <-received: + if event.Event != "cli_recipes_list_completed" { + t.Fatalf("missing complete final event: %+v", event) + } + case <-time.After(time.Second): + t.Fatal("request body was truncated or not sent") + } + }) + } +} + +func TestAnalyticsDoesNotRetryOrFollowRedirects(t *testing.T) { + for _, result := range []string{"closed connection", "429", "503", "redirect"} { + t.Run(result, func(t *testing.T) { + var calls, redirected atomic.Int32 + target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { redirected.Add(1) })) + defer target.Close() + received := make(chan struct{}, 2) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = io.Copy(io.Discard, r.Body) + calls.Add(1) + received <- struct{}{} + switch result { + case "closed connection": + conn, _, err := w.(http.Hijacker).Hijack() + if err != nil { + t.Error(err) + return + } + _ = conn.Close() + case "429": + w.Header().Set("Retry-After", "60") + w.WriteHeader(http.StatusTooManyRequests) + case "503": + w.WriteHeader(http.StatusServiceUnavailable) + case "redirect": + w.Header().Set("Location", target.URL) + w.WriteHeader(http.StatusTemporaryRedirect) + } + })) + defer server.Close() + a := analyticsTestApp(t, server.URL) + for range 2 { + op := a.beginAnalytics("recipes list", "mcp") + if op == nil { + t.Fatal("a previous response suppressed a later operation") + } + op.finish(nil) + select { + case <-received: + case <-time.After(time.Second): + t.Fatal("batch not received") + } + } + if calls.Load() != 2 || redirected.Load() != 0 { + t.Fatalf("unexpected retry/redirect: calls=%d redirects=%d", calls.Load(), redirected.Load()) + } + }) + } +} + +func TestAnalyticsStalledTLSBoundsShellAndMCPCompletion(t *testing.T) { + for _, channel := range []string{"shell", "mcp"} { + t.Run(channel, func(t *testing.T) { + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer func() { _ = listener.Close() }() + stop, accepted := make(chan struct{}), make(chan struct{}) + defer close(stop) + go func() { + conn, acceptErr := listener.Accept() + if acceptErr != nil { + return + } + defer func() { _ = conn.Close() }() + close(accepted) + <-stop // Keep TLS setup stalled beyond the command's drain budget. + }() + a := analyticsTestApp(t, "https://"+listener.Addr().String()) + start := time.Now() + if channel == "shell" { + a.root = a.buildRoot() + a.root.SetArgs([]string{"recipes", "list", "--type", "invalid", "--json"}) + err = a.root.Execute() + } else { + _, err = a.callMCPTool("agora.recipes.list", map[string]any{"type": "invalid"}, nil) + } + elapsed := time.Since(start) + var businessErr *cliError + if !errors.As(err, &businessErr) || businessErr.Code != "RECIPE_TYPE_INVALID" { + t.Fatalf("telemetry changed business error: %v", err) + } + // Allow scheduling overhead around the one-second timer, but reject + // a multi-second drain such as the previous five-second budget. + if elapsed > 1500*time.Millisecond { + t.Fatalf("telemetry delayed %s completion: %s", channel, elapsed) + } + select { + case <-accepted: + case <-time.After(time.Second): + t.Fatal("test did not exercise a stalled TLS connection") + } + }) + } +} diff --git a/internal/cli/analytics_sender.go b/internal/cli/analytics_sender.go new file mode 100644 index 0000000..a7473e7 --- /dev/null +++ b/internal/cli/analytics_sender.go @@ -0,0 +1,295 @@ +package cli + +import ( + "bytes" + "encoding/json" + "io" + "net/http" + "os" + "os/exec" + "strings" + "time" +) + +const analyticsSenderCommand = "__telemetry-send" +const analyticsRequestLimit = 64 * 1024 +const analyticsHandoffTimeout = 100 * time.Millisecond + +type analyticsBatch struct { + Events []analyticsEvent `json:"events"` +} + +func (op *analyticsOperation) submit(event analyticsEvent) { + if op.batchBytes > analyticsRequestLimit || !validAnalyticsEvent(event) { + return + } + body, err := json.Marshal(event) + if err != nil { + return + } + size := op.batchBytes + if size == 0 { + size = len(`{"events":[]}`) + } + if len(op.events) > 0 { + size++ // comma between events + } + size += len(body) + op.batchBytes = size + if size > analyticsRequestLimit { + // Drop an oversized operation as a whole rather than send a partial lifecycle. + op.events = nil + return + } + op.events = append(op.events, json.RawMessage(body)) +} + +func (op *analyticsOperation) flush() { + if len(op.events) == 0 { + return + } + events := op.events + if start := op.initStarted; start != nil { + // The start keeps its original timestamp. Only source attribution can + // be added later, after resolving the public catalog entry. + for _, key := range []string{"source_type", "source_id", "recipe_id"} { + if value, ok := op.properties[key]; ok { + start.Properties[key] = value + } + } + if !validAnalyticsEvent(*start) { + return + } + first, err := json.Marshal(start) + if err != nil { + return + } + events = append([]json.RawMessage{first}, events...) + } + body, err := json.Marshal(struct { + Events []json.RawMessage `json:"events"` + }{Events: events}) + op.events = nil + if err != nil || len(body) > analyticsRequestLimit { + return + } + executable, err := os.Executable() + if err != nil { + return + } + cmd := exec.Command(executable, analyticsSenderCommand, op.endpoint) + detachAnalyticsProcess(cmd) + cmd.Env = analyticsSenderEnv() + pipe, err := cmd.StdinPipe() + if err != nil { + return + } + // nil stdout/stderr are connected to the null device by os/exec. + if err := cmd.Start(); err != nil { + _ = pipe.Close() + return + } + go func() { _ = cmd.Wait() }() + handoffAnalyticsBatch(pipe, body) +} + +func analyticsSenderEnv() []string { + // Preserve network settings without inheriting business credentials. + env := []string{} + for _, key := range []string{"HTTP_PROXY", "HTTPS_PROXY", "NO_PROXY", "http_proxy", "https_proxy", "no_proxy", "SSL_CERT_FILE", "SSL_CERT_DIR"} { + if value, ok := os.LookupEnv(key); ok { + env = append(env, key+"="+value) + } + } + return env +} + +func handoffAnalyticsBatch(pipe io.WriteCloser, body []byte) { + done := make(chan struct{}) + go func() { + defer close(done) + defer func() { _ = pipe.Close() }() + _, _ = pipe.Write(body) + }() + timer := time.NewTimer(analyticsHandoffTimeout) + defer timer.Stop() + select { + case <-done: + case <-timer.C: + _ = pipe.Close() + } +} + +// RunAnalyticsSender recognizes the private entry before config/session loading. +// Its only input is an allowlisted JSON batch; it cannot execute business commands. +func RunAnalyticsSender(args []string, input io.Reader) bool { + if len(args) == 0 || args[0] != analyticsSenderCommand { + return false + } + if len(args) == 2 { + a := &App{env: map[string]string{"AGORA_TELEMETRY_URL": args[1]}} + if endpoint := a.analyticsURL(); endpoint != "" { + sendAnalyticsBatch(input, endpoint) + } + } + return true +} + +func sendAnalyticsBatch(input io.Reader, endpoint string) { + data, err := io.ReadAll(io.LimitReader(input, analyticsRequestLimit+1)) + if err != nil || len(data) > analyticsRequestLimit { + return + } + var batch analyticsBatch + decoder := json.NewDecoder(bytes.NewReader(data)) + decoder.DisallowUnknownFields() + if decoder.Decode(&batch) != nil || len(batch.Events) == 0 { + return + } + if decoder.Decode(new(any)) != io.EOF { + return + } + for _, event := range batch.Events { + if !validAnalyticsEvent(event) { + return + } + } + body, err := json.Marshal(batch) + if err != nil || len(body) > analyticsRequestLimit { + return + } + transport := http.DefaultTransport.(*http.Transport).Clone() + defer transport.CloseIdleConnections() + client := &http.Client{Transport: transport, Timeout: analyticsSendTimeout, CheckRedirect: func(_ *http.Request, _ []*http.Request) error { return http.ErrUseLastResponse }} + req, err := http.NewRequest(http.MethodPost, endpoint, bytes.NewReader(body)) + if err != nil { + return + } + req.Header.Set("Content-Type", "application/json") + req.GetBody = nil + response, _ := client.Do(req) + if response != nil { + _ = response.Body.Close() + } +} + +// Defense in depth: never let arbitrary properties, names or raw errors enter +// the pipe, even if a future instrumentation call accidentally adds one. +func validAnalyticsEvent(e analyticsEvent) bool { + if !analyticsIDPattern.MatchString(e.EventID) || !analyticsIDPattern.MatchString(e.OperationID) || !strings.HasPrefix(e.DistinctID, "cli:") || !analyticsIDPattern.MatchString(strings.TrimPrefix(e.DistinctID, "cli:")) { + return false + } + p := e.Properties + command, _ := p["command"].(string) + switch command { + case "init": + if e.Event != "cli_init_started" && e.Event != "cli_init_stage_completed" && e.Event != "cli_init_completed" && e.Event != "cli_project_create_completed" { + return false + } + case "recipes list", "recipes show", "project create": + if e.Event != "cli_"+strings.ReplaceAll(command, " ", "_")+"_completed" { + return false + } + default: + return false + } + for key, value := range p { + str, isString := value.(string) + if key != "duration_ms" && key != "exit_code" && key != "result_count" && !isString { + return false + } + switch key { + case "command": + case "os": + if !analyticsPlatformPattern.MatchString(str) { + return false + } + case "arch": + if len(str) > 20 || !analyticsPlatformPattern.MatchString(str) { + return false + } + case "cli_version": + if !analyticsVersionPattern.MatchString(str) { + return false + } + case "invocation_channel": + if str != "shell" && str != "mcp" { + return false + } + case "agent_family": + if !oneOf(str, "codex", "claude-code", "kiro", "cursor", "cline", "windsurf", "aider", "custom", "unknown") { + return false + } + case "agent_surface": + if !oneOf(str, "desktop", "cli", "unknown") { + return false + } + case "agent_detection_source": + if !oneOf(str, "explicit", "environment", "none") { + return false + } + case "source_type": + if !oneOf(str, "recipe", "quickstart") { + return false + } + case "source_id", "recipe_id": + if len(str) > 100 || !analyticsSlugPattern.MatchString(str) { + return false + } + case "app_id": + if !analyticsAppIDPattern.MatchString(str) || strings.HasPrefix(command, "recipes ") { + return false + } + case "project_action": + if !oneOf(str, "created", "reused", "unknown") { + return false + } + case "stage", "failed_stage": + if !oneOf(str, "validate", "source_resolve", "local_validate", "project_resolve", "clone", "env_write", "binding_write", "context_write", "agent_rules_write") { + return false + } + case "outcome": + if !oneOf(str, "success", "failure", "cancelled") { + return false + } + case "error_code": + if str != "" && !analyticsCodePattern.MatchString(str) { + return false + } + case "duration_ms", "exit_code", "result_count": + var n float64 + switch v := value.(type) { + case int: + n = float64(v) + case int64: + n = float64(v) + case float64: + n = v + default: + return false + } + maxValue := float64(604800000) + if key == "exit_code" { + maxValue = 255 + } + if key == "result_count" { + maxValue = 1000000 + } + if n < 0 || n > maxValue || n != float64(int64(n)) { + return false + } + default: + return false + } + } + return true +} + +func oneOf(value string, values ...string) bool { + for _, v := range values { + if value == v { + return true + } + } + return false +} diff --git a/internal/cli/analytics_test.go b/internal/cli/analytics_test.go new file mode 100644 index 0000000..cbf467f --- /dev/null +++ b/internal/cli/analytics_test.go @@ -0,0 +1,332 @@ +package cli + +import ( + "bytes" + "encoding/json" + "errors" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "runtime" + "slices" + "strings" + "sync" + "testing" + "time" +) + +func analyticsRecorder(t *testing.T) (*httptest.Server, func() []analyticsEvent) { + t.Helper() + var mu sync.Mutex + var events []analyticsEvent + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("Authorization") != "" || r.URL.RawQuery != "" { + t.Error("analytics leaked authentication or query parameters") + } + var body struct { + Events []analyticsEvent `json:"events"` + } + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + t.Error(err) + } + mu.Lock() + events = append(events, body.Events...) + mu.Unlock() + w.WriteHeader(http.StatusAccepted) + })) + t.Cleanup(server.Close) + return server, func() []analyticsEvent { mu.Lock(); defer mu.Unlock(); return append([]analyticsEvent(nil), events...) } +} + +func analyticsTestApp(t *testing.T, endpoint string) *App { + t.Helper() + + a := &App{env: map[string]string{"AGORA_HOME": t.TempDir(), "AGORA_TELEMETRY_URL": endpoint}, osEnv: map[string]string{}, cfg: defaultConfig(), httpClient: &http.Client{Timeout: time.Second}} + if err := a.persistTelemetryChoice(true); err != nil { + t.Fatal(err) + } + return a +} + +// Sender completion no longer acknowledges server receipt. Wait on the test +// collector explicitly when an assertion needs to inspect received payloads. +func waitAnalyticsEvents(t *testing.T, read func() []analyticsEvent, count int) []analyticsEvent { + t.Helper() + return waitAnalytics(t, read, func(events []analyticsEvent) bool { return len(events) >= count }) +} + +func waitAnalytics(t *testing.T, read func() []analyticsEvent, ready func([]analyticsEvent) bool) []analyticsEvent { + t.Helper() + deadline := time.NewTimer(5 * time.Second) + defer deadline.Stop() + tick := time.NewTicker(time.Millisecond) + defer tick.Stop() + for { + events := read() + if ready(events) { + return events + } + select { + case <-tick.C: + case <-deadline.C: + t.Fatalf("collector did not receive the expected events: %+v", events) + } + } +} + +func TestAnalyticsInstallationPrivacyAndStages(t *testing.T) { + server, read := analyticsRecorder(t) + a := analyticsTestApp(t, server.URL) + a.osEnv = map[string]string{"CLAUDECODE": "1", "CLAUDE_CODE_ENTRYPOINT": "cli", "ANTHROPIC_MODEL": "private-model", "SECRET_TOKEN": "private-token"} + op := a.beginAnalytics("init", "shell") + op.source("recipe", "hotel-reception") + op.beginStage("clone") + op.finish(&cliError{Code: "RECIPE_NOT_FOUND", Message: "private-token /private/home/project"}) + events := waitAnalyticsEvents(t, read, 4) + if len(events) != 4 { + t.Fatalf("want start, two stages, final; got %+v", events) + } + for _, e := range events { + if !strings.HasPrefix(e.DistinctID, "cli:") || e.OperationID != op.id || e.Properties["source_session_id"] != nil { + t.Fatalf("bad installation identity: %+v", e) + } + } + var final analyticsEvent + for _, event := range events { + if event.Event == "cli_init_completed" { + final = event + } + } + if final.Event != "cli_init_completed" || final.Properties["failed_stage"] != "clone" || final.Properties["outcome"] != "failure" || final.Properties["agent_family"] != "claude-code" { + t.Fatalf("bad final: %+v", final) + } + b, _ := json.Marshal(events) + if strings.Contains(string(b), "private-") || strings.Contains(string(b), "/private/home") { + t.Fatalf("sensitive data leaked: %s", b) + } + next := a.beginAnalytics("recipes list", "shell") + next.finish(nil) + all := waitAnalyticsEvents(t, read, 5) + last := all[len(all)-1] + if last.DistinctID != events[0].DistinctID || last.Properties["source_session_id"] != nil || last.OperationID == op.id { + t.Fatalf("installation identity or operation isolation changed: %+v", last) + } + info, err := os.Stat(filepath.Join(a.env["AGORA_HOME"], "analytics-id")) + if err != nil { + t.Fatal(err) + } + if runtime.GOOS != "windows" && info.Mode().Perm()&0o077 != 0 { + t.Fatal("anonymous ID is not private") + } +} + +func TestAnalyticsRecipeInitAttributionAndLocalValidation(t *testing.T) { + target := t.TempDir() + for _, channel := range []string{"shell", "mcp"} { + for _, lookupFailed := range []bool{false, true} { + scenario := "existing target" + if lookupFailed { + scenario = "recipe API failure" + } + t.Run(channel+"/"+scenario, func(t *testing.T) { + collector, read := analyticsRecorder(t) + api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + if lookupFailed { + w.WriteHeader(http.StatusServiceUnavailable) + return + } + _, _ = io.WriteString(w, `{"schemaVersion":1,"recipe":{"slug":"hotel","title":"Hotel","mainRepoUrl":"https://github.com/AgoraIO/hotel","recipeRawUrl":"https://example.com/RECIPE.md","type":"ai","official":true,"cli":{"projectType":"python","env":{"examplePath":".env.example","targetPath":".env","appIdKey":"AGORA_APP_ID","appCertificateKey":"AGORA_APP_CERTIFICATE"}}}}`) + })) + defer api.Close() + a := analyticsTestApp(t, collector.URL) + a.env["AGORA_RECIPES_BASE_URL"] = api.URL + + var err error + if channel == "shell" { + a.root = a.buildRoot() + a.root.SetOut(io.Discard) + a.root.SetErr(io.Discard) + a.root.SetArgs([]string{"init", "demo", "--recipe", "hotel", "--dir", target, "--json"}) + err = a.root.Execute() + } else { + _, err = a.callMCPTool("agora.init", map[string]any{"name": "demo", "recipe": "hotel", "dir": target}, nil) + } + wantStage, wantCode, wantID := "local_validate", "QUICKSTART_TARGET_EXISTS", any("hotel") + if lookupFailed { + wantStage, wantCode, wantID = "source_resolve", "RECIPE_API_FAILED", nil + } + var businessErr *cliError + if !errors.As(err, &businessErr) || businessErr.Code != wantCode { + t.Fatalf("expected %s, got %v", wantCode, err) + } + + events := waitAnalytics(t, read, func(events []analyticsEvent) bool { + return len(events) > 0 && events[len(events)-1].Event == "cli_init_completed" + }) + first, last := events[0], events[len(events)-1] + if first.Event != "cli_init_started" || first.OperationID != last.OperationID { + t.Fatalf("unexpected init lifecycle: %+v", events) + } + for _, event := range []analyticsEvent{first, last} { + p := event.Properties + if p["source_type"] != "recipe" || p["source_id"] != wantID || p["recipe_id"] != wantID { + t.Errorf("unexpected recipe attribution for %s: %v", event.Event, p) + } + } + if last.Properties["failed_stage"] != wantStage || last.Properties["error_code"] != wantCode { + t.Errorf("unexpected failure: %v", last.Properties) + } + if !lookupFailed && !slices.ContainsFunc(events, func(e analyticsEvent) bool { + return e.Properties["stage"] == "source_resolve" && e.Properties["outcome"] == "success" + }) { + t.Error("expected source resolution to succeed before local validation") + } + }) + } + } +} + +func TestAnalyticsOptOutAndEndpointSafety(t *testing.T) { + for _, key := range []string{"DO_NOT_TRACK", "AGORA_SENTRY_ENABLED", "AGORA_TELEMETRY_ENABLED", "config", "no-endpoint", "unsafe-url"} { + t.Run(key, func(t *testing.T) { + server, read := analyticsRecorder(t) + a := analyticsTestApp(t, server.URL) + switch key { + case "config": + if err := a.persistTelemetryChoice(false); err != nil { + t.Fatal(err) + } + case "no-endpoint": + delete(a.env, "AGORA_TELEMETRY_URL") + case "unsafe-url": + a.env["AGORA_TELEMETRY_URL"] = "http://external.example/events" + case "DO_NOT_TRACK": + a.env[key] = "any-value" + default: + a.env[key] = "0" + } + op := a.beginAnalytics("init", "shell") + if op != nil { + op.finish(nil) + t.Fatal("disabled transport created an operation") + } + if len(read()) != 0 { + t.Fatal("opt out emitted events") + } + if _, err := os.Stat(filepath.Join(a.env["AGORA_HOME"], "analytics-id")); !os.IsNotExist(err) { + t.Fatal("opt out created an identity") + } + }) + } +} + +func TestAnalyticsMCPIgnoresLegacyWebIdentity(t *testing.T) { + server, read := analyticsRecorder(t) + a := analyticsTestApp(t, server.URL) + for _, args := range []map[string]any{{"sourceDistinctId": "browser", "sourceSessionId": "session"}, {"sourceDistinctId": "browser"}} { + if _, err := a.callMCPTool("agora.init", args, nil); err == nil { + t.Fatal("missing name should still fail") + } + } + events := waitAnalyticsEvents(t, read, 6) + var finals []analyticsEvent + for _, e := range events { + if e.Event == "cli_init_completed" { + finals = append(finals, e) + } + } + slices.SortFunc(finals, func(a, b analyticsEvent) int { return a.Timestamp.Compare(b.Timestamp) }) + if len(finals) != 2 || finals[0].OperationID == finals[1].OperationID || !strings.HasPrefix(finals[0].DistinctID, "cli:") || finals[0].DistinctID != finals[1].DistinctID { + t.Fatalf("bad MCP isolation: %+v", finals) + } + for _, e := range finals { + if e.Properties["invocation_channel"] != "mcp" || e.Properties["source_session_id"] != nil { + t.Fatal("wrong MCP channel") + } + } +} + +func TestAnalyticsCommandWithoutWebContext(t *testing.T) { + server, read := analyticsRecorder(t) + a := analyticsTestApp(t, server.URL) + a.root = a.buildRoot() + var out, stderr bytes.Buffer + a.root.SetOut(&out) + a.root.SetErr(&stderr) + a.root.SetArgs([]string{"recipes", "list", "--type", "invalid", "--json"}) + if err := a.root.Execute(); err == nil { + t.Fatal("invalid type should fail") + } + events := waitAnalyticsEvents(t, read, 1) + if len(events) != 1 || events[0].Event != "cli_recipes_list_completed" || events[0].Properties["error_code"] != "RECIPE_TYPE_INVALID" || !strings.HasPrefix(events[0].DistinctID, "cli:") { + t.Fatalf("bad standalone events: %+v", events) + } +} + +func TestAnalyticsNetworkFailureIsBounded(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + select { + case <-r.Context().Done(): + case <-time.After(1200 * time.Millisecond): + } + })) + defer server.Close() + a := analyticsTestApp(t, server.URL) + start := time.Now() + op := a.beginAnalytics("init", "shell") + op.finish(errors.New("private error")) + if time.Since(start) > 1500*time.Millisecond { + t.Fatal("analytics delayed command beyond bounded flush") + } +} + +func TestAnalyticsAgentClassification(t *testing.T) { + for _, tc := range []struct { + env map[string]string + family, surface, source string + }{ + {map[string]string{"CLAUDECODE": "1", "CLAUDE_CODE_ENTRYPOINT": "claude-desktop"}, "claude-code", "desktop", "environment"}, + {map[string]string{"KIRO_SESSION_ID": "private", "KIRO_CLI_ACP_CLIENT_NAME": "kiro-tui"}, "kiro", "cli", "environment"}, + {map[string]string{"CODEX_THREAD_ID": "private"}, "codex", "unknown", "environment"}, + {map[string]string{"CODEX_THREAD_ID": "private", "AGORA_AGENT_DISABLE_INFER": "1"}, "unknown", "unknown", "none"}, + {map[string]string{"AGORA_AGENT": "private custom value"}, "custom", "unknown", "explicit"}, + } { + family, surface, source := analyticsAgent(tc.env) + if family != tc.family || surface != tc.surface || source != tc.source { + t.Fatalf("classification: %s %s %s", family, surface, source) + } + } +} + +func TestAnalyticsWebIdentityInputsRemoved(t *testing.T) { + for _, command := range [][]string{{"init"}, {"recipes", "list"}, {"recipes", "show"}} { + for _, flag := range []string{"source-distinct-id", "source-session-id"} { + a := analyticsTestApp(t, "") + root := a.buildRoot() + cmd, _, err := root.Find(command) + if err != nil { + t.Fatal(err) + } + if cmd.Flags().Lookup(flag) != nil { + t.Fatalf("%v still accepts %s", command, flag) + } + root.SetOut(&bytes.Buffer{}) + root.SetErr(&bytes.Buffer{}) + root.SetArgs(append(append([]string{}, command...), "--"+flag, "legacy-web-id")) + if err := root.Execute(); err == nil || !strings.Contains(err.Error(), "unknown flag") { + t.Fatalf("legacy web flag was not rejected: %v", err) + } + } + } + for _, tool := range mcpTools() { + schema, _ := tool["inputSchema"].(map[string]any) + properties, _ := schema["properties"].(map[string]any) + for _, key := range []string{"sourceDistinctId", "sourceSessionId"} { + if _, exists := properties[key]; exists { + t.Fatalf("MCP tool %v still advertises %s", tool["name"], key) + } + } + } +} diff --git a/internal/cli/commands.go b/internal/cli/commands.go index f7879d2..fba6eab 100644 --- a/internal/cli/commands.go +++ b/internal/cli/commands.go @@ -175,7 +175,7 @@ func (a *App) buildTelemetryCommand() *cobra.Command { cmd := &cobra.Command{ Use: "telemetry", Short: "Inspect or update telemetry preferences", - Long: "Telemetry is limited to operational diagnostics and never includes tokens or app certificates. DO_NOT_TRACK=1 disables telemetry at runtime.", + Long: "Telemetry reports recipes/init/project create usage by default when a collector is configured. A first-use notice is printed to stderr. It never includes tokens or app certificates. DO_NOT_TRACK=1 disables telemetry at runtime.", Example: example(` agora telemetry status agora telemetry disable @@ -199,6 +199,7 @@ func (a *App) buildTelemetryCommand() *cobra.Command { cmd.AddCommand(&cobra.Command{ Use: "enable", Short: "Enable telemetry", + Long: telemetryDisclosure + "\n\nEnable the saved preference. Runtime opt-out still takes precedence.", Example: example(` agora telemetry enable agora telemetry enable --json @@ -228,30 +229,35 @@ func (a *App) renderTelemetry(cmd *cobra.Command) error { return err } return renderResult(cmd, "telemetry", map[string]any{ - "action": "status", - "configPath": path, - "doNotTrack": strings.TrimSpace(a.env["DO_NOT_TRACK"]) != "", - "enabled": a.cfg.TelemetryEnabled && strings.TrimSpace(a.env["DO_NOT_TRACK"]) == "", + "action": "status", + "transportConfigured": a.analyticsURL() != "", + "captureActive": a.analyticsEnabled() && a.analyticsURL() != "", + "configPath": path, + "doNotTrack": strings.TrimSpace(a.env["DO_NOT_TRACK"]) != "", + "enabled": a.analyticsEnabled(), + "savedPreference": a.cfg.TelemetryEnabled, }) } func (a *App) setTelemetry(cmd *cobra.Command, enabled bool) error { - next := a.cfg - next.TelemetryEnabled = enabled path, err := resolveConfigFilePath(a.env) if err != nil { return err } - if err := writeSecureJSON(path, next); err != nil { + if err := a.persistTelemetryChoice(enabled); err != nil { return err } - a.cfg = next - a.applyConfigToEnv() + if enabled { + a.maybeShowTelemetryNotice(cmd) + } return renderResult(cmd, "telemetry", map[string]any{ - "action": map[bool]string{true: "enable", false: "disable"}[enabled], - "configPath": path, - "enabled": enabled && strings.TrimSpace(a.env["DO_NOT_TRACK"]) == "", - "doNotTrack": strings.TrimSpace(a.env["DO_NOT_TRACK"]) != "", + "action": map[bool]string{true: "enable", false: "disable"}[enabled], + "transportConfigured": a.analyticsURL() != "", + "captureActive": a.analyticsEnabled() && a.analyticsURL() != "", + "configPath": path, + "enabled": a.analyticsEnabled(), + "savedPreference": enabled, + "doNotTrack": strings.TrimSpace(a.env["DO_NOT_TRACK"]) != "", }) } @@ -540,6 +546,9 @@ func (a *App) buildConfigCommand() *cobra.Command { } a.cfg = next a.applyConfigToEnv() + if cmd.Flags().Changed("telemetry-enabled") && telemetryEnabled { + a.maybeShowTelemetryNotice(cmd) + } return renderResult(cmd, "config update", next) }, } @@ -633,7 +642,7 @@ func (a *App) buildProjectCreate() *cobra.Command { } return renderResult(cmd, "project create", result) } - data, err := a.projectCreate(args[0], template, features, normalizedRTMDataCenter, idempotencyKey) + data, err := a.projectCreate(args[0], template, features, normalizedRTMDataCenter, idempotencyKey, analyticsFor(cmd)) if err != nil { return err } @@ -646,6 +655,7 @@ func (a *App) buildProjectCreate() *cobra.Command { cmd.Flags().BoolVar(&dryRun, "dry-run", false, "return the planned project create result without creating remote resources") cmd.Flags().StringVar(&idempotencyKey, "idempotency-key", "", "caller-provided key for safe retries when supported by the API") _ = cmd.RegisterFlagCompletionFunc("template", completeProjectPresetIDs) + a.instrumentAnalytics(cmd, "project create") return cmd } diff --git a/internal/cli/env_help.go b/internal/cli/env_help.go index eda06cd..bc9e21d 100644 --- a/internal/cli/env_help.go +++ b/internal/cli/env_help.go @@ -50,6 +50,8 @@ func agoraEnvCatalog() []agoraEnvVar { {Name: "AGORA_RECIPES_BASE_URL", Category: "endpoints", Description: "Override the versioned Agora recipes API base URL for staging and integration tests.", Default: "https://recipes.agora.io/api/v1"}, {Name: "AGORA_QUICKSTART_