Skip to content

Commit

Permalink
lint.
Browse files Browse the repository at this point in the history
  • Loading branch information
jonhadfield committed Apr 28, 2024
1 parent 7627e1a commit 3655966
Show file tree
Hide file tree
Showing 16 changed files with 49 additions and 40 deletions.
2 changes: 1 addition & 1 deletion cache/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ func CheckExists(logger *slog.Logger, db *badger.DB, key string) (bool, error) {
return nil
}

return tErr
return fmt.Errorf("error getting cache item: %w", tErr)
}

found = true
Expand Down
8 changes: 4 additions & 4 deletions cmd/cache.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package cmd

import (
_ "embed"
"fmt"
"os"

"github.com/jonhadfield/ipscout/manager"
Expand Down Expand Up @@ -46,7 +46,7 @@ func newCacheListCommand() *cobra.Command {
}

if err = mgr.List(); err != nil {
return err
return fmt.Errorf("error listing cache items: %w", err)
}

return nil
Expand All @@ -70,7 +70,7 @@ func newCacheDelCommand() *cobra.Command {
}

if err = mgr.Delete(args); err != nil {
return err
return fmt.Errorf("error deleting item from cache: %w", err)
}

return nil
Expand All @@ -96,7 +96,7 @@ func newCacheGetCommand() *cobra.Command {
}

if err = mgr.Get(args[0], raw); err != nil {
return err
return fmt.Errorf("error getting item from cache: %w", err)
}

return nil
Expand Down
1 change: 0 additions & 1 deletion cmd/root.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package cmd

import (
_ "embed"
"fmt"
"log/slog"
"net/netip"
Expand Down
3 changes: 2 additions & 1 deletion manager/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ func (c *Client) CreateItemsInfoTable(info []CacheItemInfo) (*table.Writer, erro
for _, x := range info {
tw.AppendRow(table.Row{x.Key, x.ExpiresAt.Format(timeFormat), humanize.Bytes(uint64(x.EstimatedSize)), present.DashIfEmpty(x.AppVersion)})
}

tw.SetColumnConfigs([]table.ColumnConfig{
{Number: 1, AutoMerge: false, WidthMax: MaxColumnWidth, WidthMin: 20},
})
Expand Down Expand Up @@ -199,7 +200,7 @@ func (c *Client) GetCacheItemsInfo() ([]CacheItemInfo, error) {
return nil
})
if err != nil {
return nil, err
return nil, fmt.Errorf("error reading cache: %w", err)
}

return cacheItemsInfo, nil
Expand Down
2 changes: 2 additions & 0 deletions process/process.go
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,7 @@ func initialiseProviders(runners map[string]ProviderClient, hideProgress bool) e
stopSpinnerIfActive(s)
}()
}

for name, runner := range runners {
_, runner := name, runner // https://golang.org/doc/faq#closures_and_goroutines

Expand Down Expand Up @@ -317,6 +318,7 @@ type generateTablesResults struct {

func findHosts(runners map[string]ProviderClient, hideProgress bool) (*findHostsResults, error) {
var results findHostsResults

results.Lock()
results.m = make(map[string][]byte)
results.Unlock()
Expand Down
2 changes: 1 addition & 1 deletion providers/abuseipdb/abuseipdb.go
Original file line number Diff line number Diff line change
Expand Up @@ -332,7 +332,7 @@ func fetchData(c config.Config) (*HostSearchResult, error) {
Value: result.Raw,
Created: time.Now(),
}, ResultTTL); err != nil {
return nil, err
return nil, fmt.Errorf("error caching abuseipdb response: %w", err)
}

return result, nil
Expand Down
14 changes: 8 additions & 6 deletions providers/annotated/annotated.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package annotated

import (
"crypto/sha1"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
Expand All @@ -20,8 +20,6 @@ import (

"github.com/araddon/dateparse"

_ "regexp"

"github.com/jedib0t/go-pretty/v6/table"
"github.com/jonhadfield/ipscout/cache"
"github.com/jonhadfield/ipscout/config"
Expand Down Expand Up @@ -99,7 +97,7 @@ func ReadAnnotatedPrefixesFromFile(l *slog.Logger, path string, prefixesWithAnno

err = yaml.Unmarshal(file, &pwars)
if err != nil {
return err
return fmt.Errorf("error unmarshalling yaml: %w", err)
}

for _, pwar := range pwars {
Expand Down Expand Up @@ -200,7 +198,7 @@ func generateURLsHash(urls []string) string {
sort.Strings(urls)

s := strings.Join(urls, "")
h := sha1.New()
h := sha256.New()
h.Write([]byte(s))

return hex.EncodeToString(h.Sum(nil))[:providers.CacheKeySHALen]
Expand Down Expand Up @@ -237,6 +235,7 @@ func (c *ProviderClient) CreateTable(data []byte) (*table.Writer, error) {

for prefix, annotations := range result {
tw.AppendRow(table.Row{"Prefix", dashIfEmpty(prefix.String())})

for _, anno := range annotations {
tw.AppendRow(table.Row{"Date", anno.Date})
tw.AppendRow(table.Row{"Author", anno.Author})
Expand Down Expand Up @@ -345,6 +344,7 @@ func (c *ProviderClient) loadProviderDataFromCache() (map[netip.Prefix][]annotat
if item, err := cache.Read(c.Logger, c.Cache, cacheKey); err == nil {
if item.Value != nil && len(item.Value) > 0 {
var result map[netip.Prefix][]annotation

result, err = unmarshalResponse(item.Value)
if err != nil {
return nil, fmt.Errorf("error unmarshalling cached annotated response: %w", err)
Expand Down Expand Up @@ -400,7 +400,7 @@ func LoadFilePrefixesWithAnnotationsFromPath(path string, prefixesWithAnnotation

path, err = filepath.Abs(path)
if err != nil {
return err
return fmt.Errorf("error getting absolute path: %w", err)
}

var fileCount int64
Expand Down Expand Up @@ -469,11 +469,13 @@ func dashIfEmpty(value interface{}) string {
if len(v) == 0 {
return "-"
}

return v
case *string:
if v == nil || len(*v) == 0 {
return "-"
}

return *v
case int:
return fmt.Sprintf("%d", v)
Expand Down
2 changes: 1 addition & 1 deletion providers/annotated/annotated_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ func initialiseSetup(homeDir string) (*ProviderClient, error) {

db, err := cache.Create(lg, filepath.Join(homeDir, ".config", "ipscout"))
if err != nil {
return nil, err
return nil, fmt.Errorf("error creating cache: %w", err)
}

c, err := NewProviderClient(config.Config{
Expand Down
9 changes: 5 additions & 4 deletions providers/aws/aws.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ func (c *ProviderClient) loadProviderData() error {

data, err := json.Marshal(doc)
if err != nil {
return err
return fmt.Errorf("error marshalling aws provider doc: %w", err)
}

return cache.UpsertWithTTL(c.Logger, c.Cache, cache.Item{
Expand Down Expand Up @@ -104,7 +104,7 @@ func (c *ProviderClient) Initialise() error {

ok, err := cache.CheckExists(c.Logger, c.Cache, providers.CacheProviderPrefix+ProviderName)
if err != nil {
return err
return fmt.Errorf("error checking cache for aws provider data: %w", err)
}

if ok {
Expand Down Expand Up @@ -291,9 +291,9 @@ func (c *ProviderClient) CreateTable(data []byte) (*table.Writer, error) {
c.Stats.Mu.Unlock()
}()

var err error
var result HostSearchResult
if err = json.Unmarshal(data, &result); err != nil {

if err := json.Unmarshal(data, &result); err != nil {
switch {
case errors.Is(err, providers.ErrNoDataFound):
return nil, fmt.Errorf("data not loaded: %w", err)
Expand All @@ -309,6 +309,7 @@ func (c *ProviderClient) CreateTable(data []byte) (*table.Writer, error) {

tw := table.NewWriter()
var rows []table.Row

tw.AppendRow(table.Row{"Prefix", dashIfEmpty(result.Prefix.IPPrefix.String())})
tw.AppendRow(table.Row{"Service", dashIfEmpty(result.Prefix.Service)})
tw.AppendRow(table.Row{"Region", dashIfEmpty(result.Prefix.Region)})
Expand Down
12 changes: 1 addition & 11 deletions providers/azure/azure.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,16 +28,6 @@ type Config struct {
APIKey string
}

func unmarshalResponse(rBody []byte) (*HostSearchResult, error) {
var res *HostSearchResult

if err := json.Unmarshal(rBody, &res); err != nil {
return nil, err
}

return res, nil
}

func unmarshalProviderData(rBody []byte) (*azure.Doc, error) {
var res *azure.Doc

Expand Down Expand Up @@ -328,7 +318,7 @@ func (c *ProviderClient) CreateTable(data []byte) (*table.Writer, error) {
func loadResultsFile(path string) (res *HostSearchResult, err error) {
jf, err := os.Open(path)
if err != nil {
return nil, err
return nil, fmt.Errorf("error opening file: %w", err)
}

defer jf.Close()
Expand Down
6 changes: 4 additions & 2 deletions providers/criminalip/criminalip.go
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ func fetchData(client config.Config) (*HostSearchResult, error) {
Value: result.Raw,
Created: time.Now(),
}, ResultTTL); err != nil {
return nil, err
return nil, fmt.Errorf("error caching criminal ip response: %w", err)
}

return result, nil
Expand Down Expand Up @@ -357,6 +357,7 @@ func (c *ProviderClient) CreateTable(data []byte) (*table.Writer, error) {
}

var portsDisplayed int

for x, port := range portDataForTable.entries {
if !port.AgeMatch || !port.NetworkMatch {
continue
Expand Down Expand Up @@ -403,6 +404,7 @@ func (c *ProviderClient) CreateTable(data []byte) (*table.Writer, error) {
})
tw.SetAutoIndex(false)
tw.SetTitle("CRIMINAL IP | Host: %s", c.Host.String())

if c.UseTestData {
tw.SetTitle("CRIMINAL IP | Host: %s", result.IP)
}
Expand All @@ -422,7 +424,7 @@ func loadResultsFile(path string) (res *HostSearchResult, err error) {

err = decoder.Decode(&res)
if err != nil {
return res, err
return res, fmt.Errorf("error decoding criminalip data: %w", err)
}

return res, nil
Expand Down
7 changes: 5 additions & 2 deletions providers/digitalocean/digitalocean.go
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ func (c *ProviderClient) Initialise() error {
// load provider data into cache if not already present and fresh
ok, err := cache.CheckExists(c.Logger, c.Cache, providers.CacheProviderPrefix+ProviderName)
if err != nil {
return err
return fmt.Errorf("checking digitalocean cache: %w", err)
}

if ok {
Expand Down Expand Up @@ -258,6 +258,7 @@ func (c *ProviderClient) CreateTable(data []byte) (*table.Writer, error) {

tw := table.NewWriter()
var rows []table.Row

tw.AppendRow(table.Row{"Prefix", dashIfEmpty(result.Record.NetworkText)})
tw.AppendRow(table.Row{"Country Code", dashIfEmpty(result.Record.CountryCode)})
tw.AppendRow(table.Row{"City Name", dashIfEmpty(result.Record.CityName)})
Expand Down Expand Up @@ -287,7 +288,7 @@ func (c *ProviderClient) CreateTable(data []byte) (*table.Writer, error) {
func loadResultsFile(path string) (res *HostSearchResult, err error) {
jf, err := os.Open(path)
if err != nil {
return nil, err
return nil, fmt.Errorf("error opening file: %w", err)
}

defer jf.Close()
Expand Down Expand Up @@ -315,11 +316,13 @@ func dashIfEmpty(value interface{}) string {
if len(v) == 0 {
return "-"
}

return v
case *string:
if v == nil || len(*v) == 0 {
return "-"
}

return *v
case int:
return fmt.Sprintf("%d", v)
Expand Down
9 changes: 5 additions & 4 deletions providers/ipurl/ipurl.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package ipurl

import (
"crypto/sha1"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
Expand All @@ -20,7 +20,7 @@ import (

const (
ProviderName = "ipurl"
CacheTTL = time.Duration(3 * time.Hour)
CacheTTL = 3 * time.Hour
)

type Config struct {
Expand Down Expand Up @@ -159,7 +159,7 @@ func (c *ProviderClient) refreshURLCache() error {

// generateURLHash concatenates the provider name and the url string and returns a hash
func generateURLHash(us string) string {
h := sha1.New()
h := sha256.New()
h.Write([]byte(us))
r := hex.EncodeToString(h.Sum(nil))

Expand Down Expand Up @@ -215,7 +215,7 @@ func (c *ProviderClient) loadProviderURLFromSource(pURL string) ([]netip.Prefix,

hfPrefixes, err := hf.FetchPrefixes()
if err != nil {
return nil, err
return nil, fmt.Errorf("error fetching ipurl data: %w", err)
}

// cache the prefixes for this url
Expand Down Expand Up @@ -321,6 +321,7 @@ func (c *ProviderClient) CreateTable(data []byte) (*table.Writer, error) {

for prefix, urls := range result {
tw.AppendRow(table.Row{"", color.CyanString(prefix.String())})

for _, url := range urls {
tw.AppendRow(table.Row{"", fmt.Sprintf("%s %s", IndentPipeHyphens, url)})
}
Expand Down
2 changes: 2 additions & 0 deletions providers/providers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,7 @@ func TestPortNetworkMatchWithoutPortsSpecified(t *testing.T) {

func TestPortNetworkMatch(t *testing.T) {
ports := []string{"80", "tcp", "80/tcp"}

require.True(t, PortNetworkMatch("80", []string{}))
require.True(t, PortNetworkMatch("80", ports))
require.False(t, PortNetworkMatch("800", ports))
Expand All @@ -150,6 +151,7 @@ func TestPortNetworkMatch(t *testing.T) {

func TestPortNetworkMatchNonWideTransport(t *testing.T) {
ports := []string{"80", "80/tcp"}

require.False(t, PortNetworkMatch("50/tcp", ports))
require.True(t, PortNetworkMatch("80", []string{}))
require.True(t, PortNetworkMatch("80", ports))
Expand Down
Loading

0 comments on commit 3655966

Please sign in to comment.