Skip to content

Commit

Permalink
refact cscli - don't export functions if not required (#3224)
Browse files Browse the repository at this point in the history
* unexport subcommand constructors

* unexport internal methods

* lint + rename local variables
  • Loading branch information
mmetc authored Sep 11, 2024
1 parent 4d10e9d commit 57539f6
Show file tree
Hide file tree
Showing 16 changed files with 113 additions and 114 deletions.
86 changes: 43 additions & 43 deletions cmd/crowdsec-cli/clialert/alerts.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ import (
"github.com/crowdsecurity/crowdsec/pkg/types"
)

func DecisionsFromAlert(alert *models.Alert) string {
func decisionsFromAlert(alert *models.Alert) string {
ret := ""
decMap := make(map[string]int)

Expand Down Expand Up @@ -77,7 +77,7 @@ func (cli *cliAlerts) alertsToTable(alerts *models.GetAlertsResponse, printMachi
*alertItem.Scenario,
alertItem.Source.Cn,
alertItem.Source.GetAsNumberName(),
DecisionsFromAlert(alertItem),
decisionsFromAlert(alertItem),
*alertItem.StartAt,
}
if printMachine {
Expand Down Expand Up @@ -227,10 +227,10 @@ func (cli *cliAlerts) NewCommand() *cobra.Command {
},
}

cmd.AddCommand(cli.NewListCmd())
cmd.AddCommand(cli.NewInspectCmd())
cmd.AddCommand(cli.NewFlushCmd())
cmd.AddCommand(cli.NewDeleteCmd())
cmd.AddCommand(cli.newListCmd())
cmd.AddCommand(cli.newInspectCmd())
cmd.AddCommand(cli.newFlushCmd())
cmd.AddCommand(cli.newDeleteCmd())

return cmd
}
Expand Down Expand Up @@ -323,7 +323,7 @@ func (cli *cliAlerts) list(alertListFilter apiclient.AlertsListOpts, limit *int,
return nil
}

func (cli *cliAlerts) NewListCmd() *cobra.Command {
func (cli *cliAlerts) newListCmd() *cobra.Command {
alertListFilter := apiclient.AlertsListOpts{
ScopeEquals: new(string),
ValueEquals: new(string),
Expand Down Expand Up @@ -377,53 +377,53 @@ cscli alerts list --type ban`,
return cmd
}

func (cli *cliAlerts) delete(alertDeleteFilter apiclient.AlertsDeleteOpts, ActiveDecision *bool, AlertDeleteAll bool, delAlertByID string, contained *bool) error {
func (cli *cliAlerts) delete(delFilter apiclient.AlertsDeleteOpts, activeDecision *bool, deleteAll bool, delAlertByID string, contained *bool) error {
var err error

if !AlertDeleteAll {
*alertDeleteFilter.ScopeEquals, err = SanitizeScope(*alertDeleteFilter.ScopeEquals, *alertDeleteFilter.IPEquals, *alertDeleteFilter.RangeEquals)
if !deleteAll {
*delFilter.ScopeEquals, err = SanitizeScope(*delFilter.ScopeEquals, *delFilter.IPEquals, *delFilter.RangeEquals)
if err != nil {
return err
}

if ActiveDecision != nil {
alertDeleteFilter.ActiveDecisionEquals = ActiveDecision
if activeDecision != nil {
delFilter.ActiveDecisionEquals = activeDecision
}

if *alertDeleteFilter.ScopeEquals == "" {
alertDeleteFilter.ScopeEquals = nil
if *delFilter.ScopeEquals == "" {
delFilter.ScopeEquals = nil
}

if *alertDeleteFilter.ValueEquals == "" {
alertDeleteFilter.ValueEquals = nil
if *delFilter.ValueEquals == "" {
delFilter.ValueEquals = nil
}

if *alertDeleteFilter.ScenarioEquals == "" {
alertDeleteFilter.ScenarioEquals = nil
if *delFilter.ScenarioEquals == "" {
delFilter.ScenarioEquals = nil
}

if *alertDeleteFilter.IPEquals == "" {
alertDeleteFilter.IPEquals = nil
if *delFilter.IPEquals == "" {
delFilter.IPEquals = nil
}

if *alertDeleteFilter.RangeEquals == "" {
alertDeleteFilter.RangeEquals = nil
if *delFilter.RangeEquals == "" {
delFilter.RangeEquals = nil
}

if contained != nil && *contained {
alertDeleteFilter.Contains = new(bool)
delFilter.Contains = new(bool)
}

limit := 0
alertDeleteFilter.Limit = &limit
delFilter.Limit = &limit
} else {
limit := 0
alertDeleteFilter = apiclient.AlertsDeleteOpts{Limit: &limit}
delFilter = apiclient.AlertsDeleteOpts{Limit: &limit}
}

var alerts *models.DeleteAlertsResponse
if delAlertByID == "" {
alerts, _, err = cli.client.Alerts.Delete(context.Background(), alertDeleteFilter)
alerts, _, err = cli.client.Alerts.Delete(context.Background(), delFilter)
if err != nil {
return fmt.Errorf("unable to delete alerts: %w", err)
}
Expand All @@ -439,14 +439,14 @@ func (cli *cliAlerts) delete(alertDeleteFilter apiclient.AlertsDeleteOpts, Activ
return nil
}

func (cli *cliAlerts) NewDeleteCmd() *cobra.Command {
func (cli *cliAlerts) newDeleteCmd() *cobra.Command {
var (
ActiveDecision *bool
AlertDeleteAll bool
activeDecision *bool
deleteAll bool
delAlertByID string
)

alertDeleteFilter := apiclient.AlertsDeleteOpts{
delFilter := apiclient.AlertsDeleteOpts{
ScopeEquals: new(string),
ValueEquals: new(string),
ScenarioEquals: new(string),
Expand All @@ -467,32 +467,32 @@ cscli alerts delete -s crowdsecurity/ssh-bf"`,
Aliases: []string{"remove"},
Args: cobra.ExactArgs(0),
PreRunE: func(cmd *cobra.Command, _ []string) error {
if AlertDeleteAll {
if deleteAll {
return nil
}
if *alertDeleteFilter.ScopeEquals == "" && *alertDeleteFilter.ValueEquals == "" &&
*alertDeleteFilter.ScenarioEquals == "" && *alertDeleteFilter.IPEquals == "" &&
*alertDeleteFilter.RangeEquals == "" && delAlertByID == "" {
if *delFilter.ScopeEquals == "" && *delFilter.ValueEquals == "" &&
*delFilter.ScenarioEquals == "" && *delFilter.IPEquals == "" &&
*delFilter.RangeEquals == "" && delAlertByID == "" {
_ = cmd.Usage()
return errors.New("at least one filter or --all must be specified")
}

return nil
},
RunE: func(cmd *cobra.Command, _ []string) error {
return cli.delete(alertDeleteFilter, ActiveDecision, AlertDeleteAll, delAlertByID, contained)
return cli.delete(delFilter, activeDecision, deleteAll, delAlertByID, contained)
},
}

flags := cmd.Flags()
flags.SortFlags = false
flags.StringVar(alertDeleteFilter.ScopeEquals, "scope", "", "the scope (ie. ip,range)")
flags.StringVarP(alertDeleteFilter.ValueEquals, "value", "v", "", "the value to match for in the specified scope")
flags.StringVarP(alertDeleteFilter.ScenarioEquals, "scenario", "s", "", "the scenario (ie. crowdsecurity/ssh-bf)")
flags.StringVarP(alertDeleteFilter.IPEquals, "ip", "i", "", "Source ip (shorthand for --scope ip --value <IP>)")
flags.StringVarP(alertDeleteFilter.RangeEquals, "range", "r", "", "Range source ip (shorthand for --scope range --value <RANGE>)")
flags.StringVar(delFilter.ScopeEquals, "scope", "", "the scope (ie. ip,range)")
flags.StringVarP(delFilter.ValueEquals, "value", "v", "", "the value to match for in the specified scope")
flags.StringVarP(delFilter.ScenarioEquals, "scenario", "s", "", "the scenario (ie. crowdsecurity/ssh-bf)")
flags.StringVarP(delFilter.IPEquals, "ip", "i", "", "Source ip (shorthand for --scope ip --value <IP>)")
flags.StringVarP(delFilter.RangeEquals, "range", "r", "", "Range source ip (shorthand for --scope range --value <RANGE>)")
flags.StringVar(&delAlertByID, "id", "", "alert ID")
flags.BoolVarP(&AlertDeleteAll, "all", "a", false, "delete all alerts")
flags.BoolVarP(&deleteAll, "all", "a", false, "delete all alerts")
flags.BoolVar(contained, "contained", false, "query decisions contained by range")

return cmd
Expand Down Expand Up @@ -538,7 +538,7 @@ func (cli *cliAlerts) inspect(details bool, alertIDs ...string) error {
return nil
}

func (cli *cliAlerts) NewInspectCmd() *cobra.Command {
func (cli *cliAlerts) newInspectCmd() *cobra.Command {
var details bool

cmd := &cobra.Command{
Expand All @@ -561,7 +561,7 @@ func (cli *cliAlerts) NewInspectCmd() *cobra.Command {
return cmd
}

func (cli *cliAlerts) NewFlushCmd() *cobra.Command {
func (cli *cliAlerts) newFlushCmd() *cobra.Command {
var (
maxItems int
maxAge string
Expand Down
2 changes: 1 addition & 1 deletion cmd/crowdsec-cli/clialert/table.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ func alertsTable(out io.Writer, wantColor string, alerts *models.GetAlertsRespon
*alertItem.Scenario,
alertItem.Source.Cn,
alertItem.Source.GetAsNumberName(),
DecisionsFromAlert(alertItem),
decisionsFromAlert(alertItem),
*alertItem.StartAt,
}

Expand Down
26 changes: 13 additions & 13 deletions cmd/crowdsec-cli/clihub/item_metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,34 +16,34 @@ import (
"github.com/crowdsecurity/crowdsec/pkg/cwhub"
)

func ShowMetrics(prometheusURL string, hubItem *cwhub.Item, wantColor string) error {
func showMetrics(prometheusURL string, hubItem *cwhub.Item, wantColor string) error {
switch hubItem.Type {
case cwhub.PARSERS:
metrics := GetParserMetric(prometheusURL, hubItem.Name)
metrics := getParserMetric(prometheusURL, hubItem.Name)
parserMetricsTable(color.Output, wantColor, hubItem.Name, metrics)
case cwhub.SCENARIOS:
metrics := GetScenarioMetric(prometheusURL, hubItem.Name)
metrics := getScenarioMetric(prometheusURL, hubItem.Name)
scenarioMetricsTable(color.Output, wantColor, hubItem.Name, metrics)
case cwhub.COLLECTIONS:
for _, sub := range hubItem.SubItems() {
if err := ShowMetrics(prometheusURL, sub, wantColor); err != nil {
if err := showMetrics(prometheusURL, sub, wantColor); err != nil {
return err
}
}
case cwhub.APPSEC_RULES:
metrics := GetAppsecRuleMetric(prometheusURL, hubItem.Name)
metrics := getAppsecRuleMetric(prometheusURL, hubItem.Name)
appsecMetricsTable(color.Output, wantColor, hubItem.Name, metrics)
default: // no metrics for this item type
}

return nil
}

// GetParserMetric is a complete rip from prom2json
func GetParserMetric(url string, itemName string) map[string]map[string]int {
// getParserMetric is a complete rip from prom2json
func getParserMetric(url string, itemName string) map[string]map[string]int {
stats := make(map[string]map[string]int)

result := GetPrometheusMetric(url)
result := getPrometheusMetric(url)
for idx, fam := range result {
if !strings.HasPrefix(fam.Name, "cs_") {
continue
Expand Down Expand Up @@ -131,7 +131,7 @@ func GetParserMetric(url string, itemName string) map[string]map[string]int {
return stats
}

func GetScenarioMetric(url string, itemName string) map[string]int {
func getScenarioMetric(url string, itemName string) map[string]int {
stats := make(map[string]int)

stats["instantiation"] = 0
Expand All @@ -140,7 +140,7 @@ func GetScenarioMetric(url string, itemName string) map[string]int {
stats["pour"] = 0
stats["underflow"] = 0

result := GetPrometheusMetric(url)
result := getPrometheusMetric(url)
for idx, fam := range result {
if !strings.HasPrefix(fam.Name, "cs_") {
continue
Expand Down Expand Up @@ -195,13 +195,13 @@ func GetScenarioMetric(url string, itemName string) map[string]int {
return stats
}

func GetAppsecRuleMetric(url string, itemName string) map[string]int {
func getAppsecRuleMetric(url string, itemName string) map[string]int {
stats := make(map[string]int)

stats["inband_hits"] = 0
stats["outband_hits"] = 0

results := GetPrometheusMetric(url)
results := getPrometheusMetric(url)
for idx, fam := range results {
if !strings.HasPrefix(fam.Name, "cs_") {
continue
Expand Down Expand Up @@ -260,7 +260,7 @@ func GetAppsecRuleMetric(url string, itemName string) map[string]int {
return stats
}

func GetPrometheusMetric(url string) []*prom2json.Family {
func getPrometheusMetric(url string) []*prom2json.Family {
mfChan := make(chan *dto.MetricFamily, 1024)

// Start with the DefaultTransport for sane defaults.
Expand Down
6 changes: 3 additions & 3 deletions cmd/crowdsec-cli/clihub/items.go
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ func ListItems(out io.Writer, wantColor string, itemTypes []string, items map[st
return nil
}

func InspectItem(item *cwhub.Item, showMetrics bool, output string, prometheusURL string, wantColor string) error {
func InspectItem(item *cwhub.Item, wantMetrics bool, output string, prometheusURL string, wantColor string) error {
switch output {
case "human", "raw":
enc := yaml.NewEncoder(os.Stdout)
Expand Down Expand Up @@ -174,10 +174,10 @@ func InspectItem(item *cwhub.Item, showMetrics bool, output string, prometheusUR
fmt.Println()
}

if showMetrics {
if wantMetrics {
fmt.Printf("\nCurrent metrics: \n")

if err := ShowMetrics(prometheusURL, item, wantColor); err != nil {
if err := showMetrics(prometheusURL, item, wantColor); err != nil {
return err
}
}
Expand Down
2 changes: 1 addition & 1 deletion cmd/crowdsec-cli/clihubtest/clean.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import (
"github.com/spf13/cobra"
)

func (cli *cliHubTest) NewCleanCmd() *cobra.Command {
func (cli *cliHubTest) newCleanCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "clean",
Short: "clean [test_name]",
Expand Down
2 changes: 1 addition & 1 deletion cmd/crowdsec-cli/clihubtest/coverage.go
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ func (cli *cliHubTest) coverage(showScenarioCov bool, showParserCov bool, showAp
return nil
}

func (cli *cliHubTest) NewCoverageCmd() *cobra.Command {
func (cli *cliHubTest) newCoverageCmd() *cobra.Command {
var (
showParserCov bool
showScenarioCov bool
Expand Down
2 changes: 1 addition & 1 deletion cmd/crowdsec-cli/clihubtest/create.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import (
"github.com/crowdsecurity/crowdsec/pkg/hubtest"
)

func (cli *cliHubTest) NewCreateCmd() *cobra.Command {
func (cli *cliHubTest) newCreateCmd() *cobra.Command {
var (
ignoreParsers bool
labels map[string]string
Expand Down
2 changes: 1 addition & 1 deletion cmd/crowdsec-cli/clihubtest/eval.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import (
"github.com/spf13/cobra"
)

func (cli *cliHubTest) NewEvalCmd() *cobra.Command {
func (cli *cliHubTest) newEvalCmd() *cobra.Command {
var evalExpression string

cmd := &cobra.Command{
Expand Down
6 changes: 2 additions & 4 deletions cmd/crowdsec-cli/clihubtest/explain.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import (
"github.com/crowdsecurity/crowdsec/pkg/dumps"
)


func (cli *cliHubTest) explain(testName string, details bool, skipOk bool) error {
test, err := HubTest.LoadTestItem(testName)
if err != nil {
Expand Down Expand Up @@ -39,16 +38,15 @@ func (cli *cliHubTest) explain(testName string, details bool, skipOk bool) error

opts := dumps.DumpOpts{
Details: details,
SkipOk: skipOk,
SkipOk: skipOk,
}

dumps.DumpTree(*test.ParserAssert.TestData, *test.ScenarioAssert.PourData, opts)

return nil
}


func (cli *cliHubTest) NewExplainCmd() *cobra.Command {
func (cli *cliHubTest) newExplainCmd() *cobra.Command {
var (
details bool
skipOk bool
Expand Down
16 changes: 8 additions & 8 deletions cmd/crowdsec-cli/clihubtest/hubtest.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,14 +68,14 @@ func (cli *cliHubTest) NewCommand() *cobra.Command {
cmd.PersistentFlags().StringVar(&cscliPath, "cscli", "cscli", "Path to cscli")
cmd.PersistentFlags().BoolVar(&isAppsecTest, "appsec", false, "Command relates to appsec tests")

cmd.AddCommand(cli.NewCreateCmd())
cmd.AddCommand(cli.NewRunCmd())
cmd.AddCommand(cli.NewCleanCmd())
cmd.AddCommand(cli.NewInfoCmd())
cmd.AddCommand(cli.NewListCmd())
cmd.AddCommand(cli.NewCoverageCmd())
cmd.AddCommand(cli.NewEvalCmd())
cmd.AddCommand(cli.NewExplainCmd())
cmd.AddCommand(cli.newCreateCmd())
cmd.AddCommand(cli.newRunCmd())
cmd.AddCommand(cli.newCleanCmd())
cmd.AddCommand(cli.newInfoCmd())
cmd.AddCommand(cli.newListCmd())
cmd.AddCommand(cli.newCoverageCmd())
cmd.AddCommand(cli.newEvalCmd())
cmd.AddCommand(cli.newExplainCmd())

return cmd
}
Loading

0 comments on commit 57539f6

Please sign in to comment.