Skip to content

Commit

Permalink
cscli refact: package cli{support, machine, bouncer} (#3199)
Browse files Browse the repository at this point in the history
* cscli refact: clisupport (reuse lapi status, capi status)

* cscli refact: package clibouncer, climachine

* cscli refact: package clisupport
  • Loading branch information
mmetc authored Aug 29, 2024
1 parent b880df9 commit 0fb6468
Show file tree
Hide file tree
Showing 12 changed files with 117 additions and 108 deletions.
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package main
package clibouncer

import (
"encoding/csv"
Expand All @@ -21,19 +21,22 @@ import (
"github.com/crowdsecurity/crowdsec/cmd/crowdsec-cli/cstable"
"github.com/crowdsecurity/crowdsec/cmd/crowdsec-cli/require"
middlewares "github.com/crowdsecurity/crowdsec/pkg/apiserver/middlewares/v1"
"github.com/crowdsecurity/crowdsec/pkg/csconfig"
"github.com/crowdsecurity/crowdsec/pkg/database"
"github.com/crowdsecurity/crowdsec/pkg/database/ent"
"github.com/crowdsecurity/crowdsec/pkg/database/ent/bouncer"
"github.com/crowdsecurity/crowdsec/pkg/emoji"
"github.com/crowdsecurity/crowdsec/pkg/types"
)

type configGetter = func() *csconfig.Config

type cliBouncers struct {
db *database.Client
cfg configGetter
}

func NewCLIBouncers(cfg configGetter) *cliBouncers {
func New(cfg configGetter) *cliBouncers {
return &cliBouncers{
cfg: cfg,
}
Expand Down Expand Up @@ -156,8 +159,11 @@ func (cli *cliBouncers) listCSV(out io.Writer, bouncers ent.Bouncers) error {
return nil
}

func (cli *cliBouncers) list(out io.Writer) error {
bouncers, err := cli.db.ListBouncers()
func (cli *cliBouncers) List(out io.Writer, db *database.Client) error {
// XXX: must use the provided db object, the one in the struct might be nil
// (calling List directly skips the PersistentPreRunE)

bouncers, err := db.ListBouncers()
if err != nil {
return fmt.Errorf("unable to list bouncers: %w", err)
}
Expand Down Expand Up @@ -194,7 +200,7 @@ func (cli *cliBouncers) newListCmd() *cobra.Command {
Args: cobra.ExactArgs(0),
DisableAutoGenTag: true,
RunE: func(_ *cobra.Command, _ []string) error {
return cli.list(color.Output)
return cli.List(color.Output, cli.db)
},
}

Expand Down
42 changes: 24 additions & 18 deletions cmd/crowdsec-cli/clicapi/capi.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,11 @@ import (
"context"
"errors"
"fmt"
"io"
"net/url"
"os"

"github.com/fatih/color"
"github.com/go-openapi/strfmt"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
Expand All @@ -23,7 +25,7 @@ import (
"github.com/crowdsecurity/crowdsec/pkg/types"
)

type configGetter func() *csconfig.Config
type configGetter = func() *csconfig.Config

type cliCapi struct {
cfg configGetter
Expand Down Expand Up @@ -147,11 +149,11 @@ func (cli *cliCapi) newRegisterCmd() *cobra.Command {
return cmd
}

// QueryCAPIStatus checks if the Local API is reachable, and if the credentials are correct. It then checks if the instance is enrolle in the console.
func QueryCAPIStatus(hub *cwhub.Hub, credURL string, login string, password string) (bool, bool, error) {
// queryCAPIStatus checks if the Central API is reachable, and if the credentials are correct. It then checks if the instance is enrolle in the console.
func queryCAPIStatus(hub *cwhub.Hub, credURL string, login string, password string) (bool, bool, error) {
apiURL, err := url.Parse(credURL)
if err != nil {
return false, false, fmt.Errorf("parsing api url: %w", err)
return false, false, err
}

itemsForAPI := hub.GetInstalledListForAPI()
Expand All @@ -176,7 +178,7 @@ func QueryCAPIStatus(hub *cwhub.Hub, credURL string, login string, password stri
},
})
if err != nil {
return false, false, fmt.Errorf("new client api: %w", err)
return false, false, err
}

pw := strfmt.Password(password)
Expand All @@ -197,10 +199,11 @@ func QueryCAPIStatus(hub *cwhub.Hub, credURL string, login string, password stri
if client.IsEnrolled() {
return true, true, nil
}

return true, false, nil
}

func (cli *cliCapi) status() error {
func (cli *cliCapi) Status(out io.Writer, hub *cwhub.Hub) error {
cfg := cli.cfg()

if err := require.CAPIRegistered(cfg); err != nil {
Expand All @@ -209,24 +212,22 @@ func (cli *cliCapi) status() error {

cred := cfg.API.Server.OnlineClient.Credentials

hub, err := require.Hub(cfg, nil, nil)
if err != nil {
return err
}

log.Infof("Loaded credentials from %s", cfg.API.Server.OnlineClient.CredentialsFilePath)
log.Infof("Trying to authenticate with username %s on %s", cred.Login, cred.URL)
fmt.Fprintf(out, "Loaded credentials from %s\n", cfg.API.Server.OnlineClient.CredentialsFilePath)
fmt.Fprintf(out, "Trying to authenticate with username %s on %s\n", cred.Login, cred.URL)

auth, enrolled, err := QueryCAPIStatus(hub, cred.URL, cred.Login, cred.Password)
auth, enrolled, err := queryCAPIStatus(hub, cred.URL, cred.Login, cred.Password)
if err != nil {
return fmt.Errorf("CAPI: failed to authenticate to Central API (CAPI): %s", err)
return fmt.Errorf("failed to authenticate to Central API (CAPI): %w", err)
}

if auth {
log.Info("You can successfully interact with Central API (CAPI)")
fmt.Fprint(out, "You can successfully interact with Central API (CAPI)\n")
}

if enrolled {
log.Info("Your instance is enrolled in the console")
fmt.Fprint(out, "Your instance is enrolled in the console\n")
}

return nil
}

Expand All @@ -237,7 +238,12 @@ func (cli *cliCapi) newStatusCmd() *cobra.Command {
Args: cobra.MinimumNArgs(0),
DisableAutoGenTag: true,
RunE: func(_ *cobra.Command, _ []string) error {
return cli.status()
hub, err := require.Hub(cli.cfg(), nil, nil)
if err != nil {
return err
}

return cli.Status(color.Output, hub)
},
}

Expand Down
41 changes: 22 additions & 19 deletions cmd/crowdsec-cli/clilapi/lapi.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,14 @@ import (
"context"
"errors"
"fmt"
"io"
"net/url"
"os"
"slices"
"sort"
"strings"

"github.com/fatih/color"
"github.com/go-openapi/strfmt"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
Expand All @@ -30,10 +32,10 @@ import (

const LAPIURLPrefix = "v1"

type configGetter func() *csconfig.Config
type configGetter = func() *csconfig.Config

type cliLapi struct {
cfg configGetter
cfg configGetter
}

func New(cfg configGetter) *cliLapi {
Expand All @@ -42,19 +44,19 @@ func New(cfg configGetter) *cliLapi {
}
}

// QueryLAPIStatus checks if the Local API is reachable, and if the credentials are correct
func QueryLAPIStatus(hub *cwhub.Hub, credURL string, login string, password string) error {
// queryLAPIStatus checks if the Local API is reachable, and if the credentials are correct.
func queryLAPIStatus(hub *cwhub.Hub, credURL string, login string, password string) (bool, error) {
apiURL, err := url.Parse(credURL)
if err != nil {
return fmt.Errorf("parsing api url: %w", err)
return false, err
}

client, err := apiclient.NewDefaultClient(apiURL,
LAPIURLPrefix,
cwversion.UserAgent(),
nil)
if err != nil {
return fmt.Errorf("init default client: %w", err)
return false, err
}

pw := strfmt.Password(password)
Expand All @@ -69,30 +71,26 @@ func QueryLAPIStatus(hub *cwhub.Hub, credURL string, login string, password stri

_, _, err = client.Auth.AuthenticateWatcher(context.Background(), t)
if err != nil {
return err
return false, err
}

return nil
return true, nil
}

func (cli *cliLapi) status() error {
func (cli *cliLapi) Status(out io.Writer, hub *cwhub.Hub) error {
cfg := cli.cfg()

cred := cfg.API.Client.Credentials

hub, err := require.Hub(cfg, nil, nil)
if err != nil {
return err
}

log.Infof("Loaded credentials from %s", cfg.API.Client.CredentialsFilePath)
log.Infof("Trying to authenticate with username %s on %s", cred.Login, cred.URL)
fmt.Fprintf(out, "Loaded credentials from %s\n", cfg.API.Client.CredentialsFilePath)
fmt.Fprintf(out, "Trying to authenticate with username %s on %s\n", cred.Login, cred.URL)

if err := QueryLAPIStatus(hub, cred.URL, cred.Login, cred.Password); err != nil {
_, err := queryLAPIStatus(hub, cred.URL, cred.Login, cred.Password)
if err != nil {
return fmt.Errorf("failed to authenticate to Local API (LAPI): %w", err)
}

log.Infof("You can successfully interact with Local API (LAPI)")
fmt.Fprintf(out, "You can successfully interact with Local API (LAPI)\n")

return nil
}
Expand Down Expand Up @@ -197,7 +195,12 @@ func (cli *cliLapi) newStatusCmd() *cobra.Command {
Args: cobra.MinimumNArgs(0),
DisableAutoGenTag: true,
RunE: func(_ *cobra.Command, _ []string) error {
return cli.status()
hub, err := require.Hub(cli.cfg(), nil, nil)
if err != nil {
return err
}

return cli.Status(color.Output, hub)
},
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package main
package climachine

// Custom types for flag validation and conversion.

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package main
package climachine

import (
"encoding/csv"
Expand Down Expand Up @@ -49,12 +49,14 @@ func getLastHeartbeat(m *ent.Machine) (string, bool) {
return hb, true
}

type configGetter = func() *csconfig.Config

type cliMachines struct {
db *database.Client
cfg configGetter
}

func NewCLIMachines(cfg configGetter) *cliMachines {
func New(cfg configGetter) *cliMachines {
return &cliMachines{
cfg: cfg,
}
Expand Down Expand Up @@ -208,8 +210,11 @@ func (cli *cliMachines) listCSV(out io.Writer, machines ent.Machines) error {
return nil
}

func (cli *cliMachines) list(out io.Writer) error {
machines, err := cli.db.ListMachines()
func (cli *cliMachines) List(out io.Writer, db *database.Client) error {
// XXX: must use the provided db object, the one in the struct might be nil
// (calling List directly skips the PersistentPreRunE)

machines, err := db.ListMachines()
if err != nil {
return fmt.Errorf("unable to list machines: %w", err)
}
Expand Down Expand Up @@ -247,7 +252,7 @@ func (cli *cliMachines) newListCmd() *cobra.Command {
Args: cobra.NoArgs,
DisableAutoGenTag: true,
RunE: func(_ *cobra.Command, _ []string) error {
return cli.list(color.Output)
return cli.List(color.Output, cli.db)
},
}

Expand Down
Loading

0 comments on commit 0fb6468

Please sign in to comment.