Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 18 additions & 47 deletions pkg/analytics/posthog.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import (
"sync"
"time"

"github.com/brevdev/brev-cli/pkg/auth"
"github.com/brevdev/brev-cli/pkg/cmd/version"
"github.com/brevdev/brev-cli/pkg/files"
"github.com/google/uuid"
Expand All @@ -35,7 +34,6 @@ var (

// Stored command context for error-path capture
storedCmd *cobra.Command
storedArgs []string
storedUser string

// userStore is set via SetUserStore so GetOrCreateAnalyticsID can resolve the real user ID.
Expand Down Expand Up @@ -98,10 +96,9 @@ func IsSSHCertRequired() bool {

// RecordCommandStart should be called from PersistentPreRunE to record the start time
// and store the command context for potential error-path capture.
func RecordCommandStart(cmd *cobra.Command, args []string) {
func RecordCommandStart(cmd *cobra.Command) {
commandStartTime = time.Now()
storedCmd = cmd
storedArgs = args
}

// IsAnalyticsEnabled defaults to true; DO_NOT_TRACK and BREV_NO_ANALYTICS override.
Expand Down Expand Up @@ -204,13 +201,12 @@ func IdentifyUser(userID string) {
}

// CaptureCommand captures a CLI command invocation event (success path).
func CaptureCommand(userID string, cmd *cobra.Command, args []string) {
func CaptureCommand(userID string, cmd *cobra.Command) {
// Store for potential error-path capture
storedCmd = cmd
storedArgs = args
storedUser = userID

captureEvent(userID, cmd, args, true)
captureEvent(userID, cmd, true)
}

// CaptureCommandError captures a CLI command failure event from main.go.
Expand All @@ -219,46 +215,23 @@ func CaptureCommandError() {
if storedCmd == nil {
return
}
captureEvent(storedUser, storedCmd, storedArgs, false)
captureEvent(storedUser, storedCmd, false)
}

// brevFlagSensitive is the pflag annotation key marking a flag whose value
// must never be sent to analytics in cleartext.
const brevFlagSensitive = "brev_flag_sensitive"

// MarkFlagSensitive annotates a flag so analytics redacts its value.
// MarkFlagSensitive identifies flags that contain credentials. Command
// telemetry never records any flag values, including unmarked ones.
func MarkFlagSensitive(flags *pflag.FlagSet, name string) {
if err := flags.SetAnnotation(name, brevFlagSensitive, []string{"true"}); err != nil {
// Flag doesn't exist in this set; nothing to annotate.
_ = err
}
}

// redactFlagValue replaces credential-shaped values with a presence marker.
// Non-sensitive values pass through untouched.
func redactFlagValue(f *pflag.Flag) interface{} {
value := f.Value.String()
switch {
case value == "":
return ""
case isAnnotatedSensitive(f), auth.IsBrevAPIKey(value), isJWTShape(value):
return "[redacted]"
}
return value
}

func isAnnotatedSensitive(f *pflag.Flag) bool {
vals, ok := f.Annotations[brevFlagSensitive]
return ok && len(vals) > 0 && vals[0] == "true"
}

// isJWTShape cheaply detects a JWT: three non-empty dot-separated segments.
func isJWTShape(value string) bool {
parts := strings.Split(value, ".")
return len(parts) == 3 && parts[0] != "" && parts[1] != "" && parts[2] != ""
}

func captureEvent(userID string, cmd *cobra.Command, args []string, succeeded bool) {
func captureEvent(userID string, cmd *cobra.Command, succeeded bool) {
if !shouldCapturePostHog() {
return
}
Expand All @@ -277,18 +250,11 @@ func captureEvent(userID string, cmd *cobra.Command, args []string, succeeded bo
return
}

// Flags — redacted: credential-shaped values (Brev API keys, JWTs) and
// flags carrying the sensitive annotation report "[redacted]" only.
flagMap := make(map[string]interface{})
cmd.Flags().Visit(func(f *pflag.Flag) {
flagMap[f.Name] = redactFlagValue(f)
})
// Only record which flags were supplied; values may be arbitrary secrets.
flagMap := captureFlagPresence(cmd)

// Parent process
parentName, parentCmdline := getParentProcessInfo()

// CWD
cwd, _ := os.Getwd()
parentName, _ := getParentProcessInfo()

// Duration
var durationMs int64
Expand All @@ -315,7 +281,6 @@ func captureEvent(userID string, cmd *cobra.Command, args []string, succeeded bo
properties := posthog.NewProperties().
// Command info
Set("command", cmd.CommandPath()).
Set("args", strings.Join(args, " ")).
Set("flags", flagMap).
Set("succeeded", succeeded).
Set("duration_ms", durationMs).
Expand All @@ -326,9 +291,7 @@ func captureEvent(userID string, cmd *cobra.Command, args []string, succeeded bo
Set("go_version", runtime.Version()).
Set("cli_version", version.Version).
// Context
Set("cwd", cwd).
Set("parent_process", parentName).
Set("parent_cmdline", parentCmdline).
// Terminal
Set("is_tty", isTTY).
Set("is_stdin_piped", isStdinPiped).
Expand All @@ -350,6 +313,14 @@ func captureEvent(userID string, cmd *cobra.Command, args []string, succeeded bo
})
}

func captureFlagPresence(cmd *cobra.Command) map[string]interface{} {
flagMap := make(map[string]interface{})
cmd.Flags().Visit(func(f *pflag.Flag) {
flagMap[f.Name] = "[redacted]"
})
return flagMap
}

// CaptureFeedback sends a brev-cli-feedback event to PostHog.
// This is sent regardless of analytics opt-in since the user explicitly chose to send feedback.
func CaptureFeedback(userID, message string) {
Expand Down
51 changes: 14 additions & 37 deletions pkg/analytics/posthog_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package analytics
import (
"testing"

"github.com/brevdev/brev-cli/pkg/auth"
"github.com/brevdev/brev-cli/pkg/files"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
Expand Down Expand Up @@ -127,75 +126,53 @@ func buildFlaggedCmd(t *testing.T, setFlags func(*pflag.FlagSet)) *cobra.Command
return cmd
}

func TestCaptureEvent_RedactsSensitiveFlagValues(t *testing.T) {
func TestCaptureFlagPresenceNeverIncludesValues(t *testing.T) {
tests := []struct {
name string
setFlags func(*pflag.FlagSet)
flagName string
wantValue interface{}
}{
{
name: "annotated flag is redacted",
name: "annotated secret flag",
setFlags: func(fs *pflag.FlagSet) {
fs.String("api-key", "bak-secret-value", "")
MarkFlagSensitive(fs, "api-key")
fs.String("value", "arbitrary provider password", "")
MarkFlagSensitive(fs, "value")
},
flagName: "api-key",
flagName: "value",
wantValue: "[redacted]",
},
{
name: "brev api key shape is redacted even unannotated",
name: "unannotated secret flag",
setFlags: func(fs *pflag.FlagSet) {
fs.String("something", auth.BrevAPIKeyPrefix+"raw-key", "")
fs.String("value", "arbitrary provider password", "")
},
flagName: "something",
flagName: "value",
wantValue: "[redacted]",
},
{
name: "jwt shape is redacted even unannotated",
name: "empty flag value",
setFlags: func(fs *pflag.FlagSet) {
fs.String("token", "eyJhbGciOi.J123.abc_sig", "")
fs.String("value", "", "")
},
flagName: "token",
flagName: "value",
wantValue: "[redacted]",
},
{
name: "benign flag passes through",
name: "ordinary flag value is also omitted",
setFlags: func(fs *pflag.FlagSet) {
fs.Bool("show-all", true, "")
fs.String("org", "my-org", "")
},
flagName: "org",
wantValue: "my-org",
wantValue: "[redacted]",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cmd := buildFlaggedCmd(t, tt.setFlags)
got := visitedFlagMap(cmd)
got := captureFlagPresence(cmd)
assert.Equal(t, tt.wantValue, got[tt.flagName])
})
}
}

func visitedFlagMap(cmd *cobra.Command) map[string]interface{} {
flagMap := make(map[string]interface{})
cmd.Flags().Visit(func(f *pflag.Flag) {
flagMap[f.Name] = redactFlagValue(f)
})
return flagMap
}

func TestCaptureCommandError_UsesRedactedFlags(t *testing.T) {
cmd := buildFlaggedCmd(t, func(fs *pflag.FlagSet) {
fs.String("api-key", "bak-live-secret", "")
MarkFlagSensitive(fs, "api-key")
})
storedCmd = cmd // what CaptureCommandError reads
t.Cleanup(func() { storedCmd = nil })

// The redaction itself is asserted via visitedFlagMap; this test pins the
// contract that CaptureCommandError consults the same visitor.
got := visitedFlagMap(cmd)
assert.Equal(t, "[redacted]", got["api-key"])
}
4 changes: 2 additions & 2 deletions pkg/cmd/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -163,11 +163,11 @@ func NewBrevCommand() *cobra.Command { //nolint:funlen,gocognit,gocyclo // defin
Find more information at:
https://brev.nvidia.com`,
PersistentPostRunE: func(cmd *cobra.Command, args []string) error {
analytics.CaptureCommand("", cmd, args)
analytics.CaptureCommand("", cmd)
return nil
},
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
analytics.RecordCommandStart(cmd, args)
analytics.RecordCommandStart(cmd)
breverrors.GetDefaultErrorReporter().AddTag("command", cmd.Name())
if strings.TrimSpace(orgFlag) != "" && !allowsOrgOverrideWithExternalAuth(cmd) && auth.IsAPIKeyAuthStore(loginCmdStore) {
return breverrors.NewValidationError(auth.APIKeyOrganizationOverrideNotSupportedMessage)
Expand Down
3 changes: 3 additions & 0 deletions pkg/cmd/secrets/secrets.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (
"github.com/spf13/cobra"
"google.golang.org/protobuf/types/known/timestamppb"

"github.com/brevdev/brev-cli/pkg/analytics"
"github.com/brevdev/brev-cli/pkg/cmd/cmderrors"
"github.com/brevdev/brev-cli/pkg/cmd/util"
"github.com/brevdev/brev-cli/pkg/entity"
Expand Down Expand Up @@ -165,6 +166,7 @@ The value can be passed with --value or piped via stdin:
}
cmd.Flags().StringVar(&name, "name", "", "secret name")
cmd.Flags().StringVar(&value, "value", "", "secret value (reads from stdin if omitted)")
analytics.MarkFlagSensitive(cmd.Flags(), "value")
return cmd
}

Expand Down Expand Up @@ -202,6 +204,7 @@ The value can be passed with --value or piped via stdin:
cmd.Flags().StringVar(&id, "id", "", "secret ID")
cmd.Flags().StringVar(&name, "name", "", "look up the secret by name instead of ID")
cmd.Flags().StringVar(&value, "value", "", "secret value (reads from stdin if omitted)")
analytics.MarkFlagSensitive(cmd.Flags(), "value")
return cmd
}

Expand Down
Loading