Compare commits

..

2 Commits

Author SHA1 Message Date
Miccah Castorina ca6251632e Always use version.BuildVersion 2023-08-21 07:20:48 -07:00
Hon 2c4b0ca7cb Add flag to get information if trufflehog being ran from TUI
Co-authored-by: mcastorina <m.castorina93@gmail.com>
2023-08-18 13:52:56 -07:00
13 changed files with 62 additions and 461 deletions
+10 -7
View File
@@ -105,11 +105,11 @@ var (
filesystemScanIncludePaths = filesystemScan.Flag("include-paths", "Path to file with newline separated regexes for files to include in scan.").Short('i').String()
filesystemScanExcludePaths = filesystemScan.Flag("exclude-paths", "Path to file with newline separated regexes for files to exclude in scan.").Short('x').String()
s3Scan = cli.Command("s3", "Find credentials in S3 buckets.")
s3ScanKey = s3Scan.Flag("key", "S3 key used to authenticate. Can be provided with environment variable AWS_ACCESS_KEY_ID.").Envar("AWS_ACCESS_KEY_ID").String()
s3ScanRoleArns = s3Scan.Flag("role-arn", "Specify the ARN of an IAM role to assume for scanning. You can repeat this flag.").Strings()
s3ScanSecret = s3Scan.Flag("secret", "S3 secret used to authenticate. Can be provided with environment variable AWS_SECRET_ACCESS_KEY.").Envar("AWS_SECRET_ACCESS_KEY").String()
s3ScanSessionToken = s3Scan.Flag("session-token", "S3 session token used to authenticate temporary credentials. Can be provided with environment variable AWS_SESSION_TOKEN.").Envar("AWS_SESSION_TOKEN").String()
s3Scan = cli.Command("s3", "Find credentials in S3 buckets.")
s3ScanKey = s3Scan.Flag("key", "S3 key used to authenticate. Can be provided with environment variable AWS_ACCESS_KEY_ID.").Envar("AWS_ACCESS_KEY_ID").String()
s3ScanRoleArns = s3Scan.Flag("role-arn", "Specify the ARN of an IAM role to assume for scanning. You can repeat this flag.").Strings()
s3ScanSecret = s3Scan.Flag("secret", "S3 secret used to authenticate. Can be provided with environment variable AWS_SECRET_ACCESS_KEY.").Envar("AWS_SECRET_ACCESS_KEY").String()
s3ScanSessionToken = s3Scan.Flag("session-token", "S3 session token used to authenticate temporary credentials. Can be provided with environment variable AWS_SESSION_TOKEN.").Envar("AWS_SESSION_TOKEN").String()
s3ScanCloudEnv = s3Scan.Flag("cloud-environment", "Use IAM credentials in cloud environment.").Bool()
s3ScanBuckets = s3Scan.Flag("bucket", "Name of S3 bucket to scan. You can repeat this flag.").Strings()
s3ScanMaxObjectSize = s3Scan.Flag("max-object-size", "Maximum size of objects to scan. Objects larger than this will be skipped. (Byte units eg. 512B, 2KB, 4MB)").Default("250MB").Bytes()
@@ -138,6 +138,8 @@ var (
dockerScan = cli.Command("docker", "Scan Docker Image")
dockerScanImages = dockerScan.Flag("image", "Docker image to scan. Use the file:// prefix to point to a local tarball, otherwise a image registry is assumed.").Required().Strings()
usingTUI = false
)
func init() {
@@ -160,6 +162,7 @@ func init() {
// Overwrite the Args slice so overseer works properly.
os.Args = os.Args[:1]
os.Args = append(os.Args, args...)
usingTUI = true
}
cmd = kingpin.MustParse(cli.Parse(os.Args[1:]))
@@ -199,7 +202,7 @@ func main() {
}
if !*noUpdate {
updateCfg.Fetcher = updater.Fetcher(version.BuildVersion)
updateCfg.Fetcher = updater.Fetcher(usingTUI)
}
if version.BuildVersion == "dev" {
updateCfg.Fetcher = nil
@@ -469,7 +472,7 @@ func run(state overseer.State) {
Secret: *s3ScanSecret,
SessionToken: *s3ScanSessionToken,
Buckets: *s3ScanBuckets,
Roles: *s3ScanRoleArns,
Roles: *s3ScanRoleArns,
CloudCred: *s3ScanCloudEnv,
MaxObjectSize: int64(*s3ScanMaxObjectSize),
}
@@ -88,7 +88,7 @@ func startSqlServer() error {
return nil
case <-time.After(30 * time.Second):
stopSqlServer()
return errors.New("timeout waiting for sql server database to be ready")
return errors.New("timeout waiting for mysql database to be ready")
}
}
+2 -9
View File
@@ -5,7 +5,6 @@ import (
"database/sql"
"regexp"
mssql "github.com/denisenkom/go-mssqldb"
"github.com/denisenkom/go-mssqldb/msdsn"
"github.com/trufflesecurity/trufflehog/v3/pkg/pb/detectorspb"
@@ -50,15 +49,9 @@ func (s Scanner) FromData(ctx context.Context, verify bool, data []byte) (result
if verify {
verified, err := ping(paramsUnsafe)
detected.Verified = verified
if mssqlErr, isMssqlErr := err.(mssql.Error); isMssqlErr && mssqlErr.Number == 18456 {
// Login failed
// Number taken from https://learn.microsoft.com/en-us/sql/relational-databases/errors-events/database-engine-events-and-errors?view=sql-server-ver16
// Nothing to do; determinate failure to verify
if err != nil {
} else {
detected.VerificationError = err
detected.Verified = verified
}
}
@@ -1,209 +0,0 @@
//go:build detectors && integration
// +build detectors,integration
package sqlserver
import (
"bytes"
"context"
"errors"
"os/exec"
"strings"
"testing"
"time"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"github.com/trufflesecurity/trufflehog/v3/pkg/detectors"
"github.com/trufflesecurity/trufflehog/v3/pkg/pb/detectorspb"
)
func TestSQLServerIntegration_FromChunk(t *testing.T) {
type args struct {
ctx context.Context
data []byte
verify bool
}
tests := []struct {
name string
s Scanner
args args
want []detectors.Result
wantErr bool
wantVerificationErr bool
}{
{
name: "found, verified",
s: Scanner{},
args: args{
ctx: context.Background(),
data: []byte("Server=localhost;Initial Catalog=master;User ID=sa;Password=P@ssw0rd!;Persist Security Info=true;MultipleActiveResultSets=true;"),
verify: true,
},
want: []detectors.Result{
{
DetectorType: detectorspb.DetectorType_SQLServer,
Raw: []byte("P@ssw0rd!"),
RawV2: []byte("sqlserver://sa:P%40ssw0rd%21@localhost?database=master&disableRetry=false"),
Redacted: "sqlserver://sa:********@localhost?database=master&disableRetry=false",
Verified: true,
},
},
wantErr: false,
},
{
name: "found, unverified",
s: Scanner{},
args: args{
ctx: context.Background(),
data: []byte("Server=localhost;User ID=sa;Password=123"),
verify: true,
},
want: []detectors.Result{
{
DetectorType: detectorspb.DetectorType_SQLServer,
Raw: []byte("123"),
RawV2: []byte("sqlserver://sa:123@localhost?disableRetry=false"),
Redacted: "sqlserver://sa:********@localhost?disableRetry=false",
Verified: false,
},
},
wantErr: false,
},
{
name: "not found, in XML, missing password param (pwd is not valid)",
s: Scanner{},
args: args{
ctx: context.Background(),
data: []byte(`<add name="Sample2" value="SERVER=server_name;DATABASE=database_name;user=user_name;pwd=plaintextpassword;encrypt=true;Timeout=120;MultipleActiveResultSets=True;" />`),
verify: true,
},
want: nil,
wantErr: false,
},
{
name: "found, verified, in XML",
s: Scanner{},
args: args{
ctx: context.Background(),
data: []byte(`<add name="test db" value="SERVER=localhost;DATABASE=master;user=sa;password=P@ssw0rd!;encrypt=true;Timeout=120;MultipleActiveResultSets=True;" />`),
verify: true,
},
want: []detectors.Result{
{
DetectorType: detectorspb.DetectorType_SQLServer,
Redacted: "sqlserver://sa:********@localhost?database=master&disableRetry=false",
Raw: []byte("P@ssw0rd!"),
RawV2: []byte("sqlserver://sa:P%40ssw0rd%21@localhost?database=master&disableRetry=false"),
Verified: true,
},
},
wantErr: false,
},
{
name: "found, unreachable host",
s: Scanner{},
args: args{
ctx: context.Background(),
data: []byte("Server=unreachablehost;Initial Catalog=master;User ID=sa;Password=P@ssw0rd!;Persist Security Info=true;MultipleActiveResultSets=true;"),
verify: true,
},
want: []detectors.Result{
{
DetectorType: detectorspb.DetectorType_SQLServer,
Raw: []byte("P@ssw0rd!"),
RawV2: []byte("sqlserver://sa:P%40ssw0rd%21@unreachablehost?database=master&disableRetry=false"),
Redacted: "sqlserver://sa:********@unreachablehost?database=master&disableRetry=false",
Verified: false,
},
},
wantErr: false,
wantVerificationErr: true,
},
{
name: "not found",
s: Scanner{},
args: args{
ctx: context.Background(),
data: []byte("You cannot find the secret within"),
verify: true,
},
want: nil,
wantErr: false,
},
}
if err := startSqlServer(); err != nil {
t.Fatalf("could not start sql server for integration testing: %v", err)
}
defer stopSqlServer()
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
s := Scanner{}
got, err := s.FromData(tt.args.ctx, tt.args.verify, tt.args.data)
if (err != nil) != tt.wantErr {
t.Errorf("SQLServer.FromData() error = %v, wantErr %v", err, tt.wantErr)
return
}
for i := range got {
if len(got[i].Raw) == 0 {
t.Fatalf("no raw secret present: \n %+v", got[i])
}
if (got[i].VerificationError != nil) != tt.wantVerificationErr {
t.Fatalf("wantVerificationError = %v, verification error = %v", tt.wantVerificationErr, got[i].VerificationError)
}
}
ignoreOpts := cmpopts.IgnoreFields(detectors.Result{}, "VerificationError")
if diff := cmp.Diff(got, tt.want, ignoreOpts); diff != "" {
t.Errorf("SQLServer.FromData() %s diff: (-got +want)\n%s", tt.name, diff)
}
})
}
}
var sqlServerDockerHash string
func dockerLogLine(hash string, needle string) chan struct{} {
ch := make(chan struct{}, 1)
go func() {
for {
out, err := exec.Command("docker", "logs", hash).CombinedOutput()
if err != nil {
panic(err)
}
if strings.Contains(string(out), needle) {
ch <- struct{}{}
return
}
time.Sleep(1 * time.Second)
}
}()
return ch
}
func startSqlServer() error {
cmd := exec.Command(
"docker", "run", "--rm", "-p", "1433:1433",
"-e", "ACCEPT_EULA=1",
"-e", "MSSQL_SA_PASSWORD=P@ssw0rd!",
"-d", "mcr.microsoft.com/azure-sql-edge",
)
out, err := cmd.Output()
if err != nil {
return err
}
sqlServerDockerHash = string(bytes.TrimSpace(out))
select {
case <-dockerLogLine(sqlServerDockerHash, "EdgeTelemetry starting up"):
return nil
case <-time.After(30 * time.Second):
stopSqlServer()
return errors.New("timeout waiting for sql server database to be ready")
}
}
func stopSqlServer() {
exec.Command("docker", "kill", sqlServerDockerHash).Run()
}
+36 -111
View File
@@ -273,65 +273,6 @@ func (s *Source) Init(aCtx context.Context, name string, jobID, sourceID int64,
return nil
}
// Validate is used by enterprise CLI to validate the Github config file.
func (s *Source) Validate(ctx context.Context) []error {
var (
errs []error
ghClient *github.Client
err error
)
apiEndpoint := s.conn.Endpoint
switch cred := s.conn.GetCredential().(type) {
case *sourcespb.GitHub_BasicAuth:
s.httpClient.Transport = &github.BasicAuthTransport{
Username: cred.BasicAuth.Username,
Password: cred.BasicAuth.Password,
}
ghClient, err = createGitHubClient(s.httpClient, apiEndpoint)
if err != nil {
errs = append(errs, fmt.Errorf("error creating GitHub client: %+v", err))
}
case *sourcespb.GitHub_Unauthenticated:
ghClient, err = createGitHubClient(s.httpClient, apiEndpoint)
if err != nil {
errs = append(errs, fmt.Errorf("error creating GitHub client: %+v", err))
}
case *sourcespb.GitHub_Token:
s.githubToken = cred.Token
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: s.githubToken},
)
s.httpClient.Transport = &oauth2.Transport{
Base: s.httpClient.Transport,
Source: oauth2.ReuseTokenSource(nil, ts),
}
ghClient, err = createGitHubClient(s.httpClient, apiEndpoint)
if err != nil {
errs = append(errs, fmt.Errorf("error creating GitHub client: %+v", err))
}
default:
errs = append(errs, errors.Errorf("Invalid configuration given for source. Name: %s, Type: %s", s.name, s.Type()))
}
// Run a simple query to check if the client is actually valid
if ghClient != nil {
err = checkGitHubConnection(ctx, ghClient)
if err != nil {
errs = append(errs, err)
}
}
return errs
}
func checkGitHubConnection(ctx context.Context, client *github.Client) error {
_, _, err := client.Users.Get(ctx, "")
return err
}
func (s *Source) visibilityOf(ctx context.Context, repoURL string) (visibility source_metadatapb.Visibility) {
s.mu.Lock()
visibility, ok := s.publicMap[repoURL]
@@ -416,11 +357,6 @@ func (s *Source) Chunks(ctx context.Context, chunksChan chan *sources.Chunk) err
apiEndpoint = "https://api.github.com"
}
// Reset consumption and rate limit metrics on each run.
githubNumRateLimitEncountered.WithLabelValues(s.name).Set(0)
githubSecondsSpentRateLimited.WithLabelValues(s.name).Set(0)
githubReposScanned.WithLabelValues(s.name).Set(0)
installationClient, err := s.enumerate(ctx, apiEndpoint)
if err != nil {
return err
@@ -456,7 +392,6 @@ func (s *Source) enumerate(ctx context.Context, apiEndpoint string) (*github.Cli
}
s.repos = s.filteredRepoCache.Values()
githubReposEnumerated.WithLabelValues(s.name).Set(float64(len(s.repos)))
s.log.Info("Completed enumeration", "num_repos", len(s.repos), "num_orgs", s.orgsCache.Count(), "num_members", len(s.memberCache))
// We must sort the repos so we can resume later if necessary.
@@ -787,8 +722,6 @@ func (s *Source) scan(ctx context.Context, installationClient *github.Client, ch
return nil
}
githubReposScanned.WithLabelValues(s.name).Inc()
if err = s.scanComments(ctx, repoURL, chunksChan); err != nil {
scanErrs.Add(fmt.Errorf("error scanning comments in repo %s: %w", repoURL, err))
return nil
@@ -818,8 +751,6 @@ func (s *Source) handleRateLimit(errIn error, res *github.Response) bool {
return false
}
githubNumRateLimitEncountered.WithLabelValues(s.name).Inc()
if res != nil {
knownWait := true
remaining, err := strconv.Atoi(res.Header.Get("x-ratelimit-remaining"))
@@ -837,7 +768,6 @@ func (s *Source) handleRateLimit(errIn error, res *github.Response) bool {
duration := time.Duration(waitTime+1) * time.Second
s.log.V(2).Info("rate limited", "resumeTime", time.Now().Add(duration).String())
time.Sleep(duration)
githubSecondsSpentRateLimited.WithLabelValues(s.name).Add(duration.Seconds())
return true
}
}
@@ -1058,51 +988,46 @@ func (s *Source) scanComments(ctx context.Context, repoPath string, chunksChan c
trimmedURL := removeURLAndSplit(repoURL.String())
if repoURL.Host == "gist.github.com" && s.includeGistComments {
return s.processGistComments(ctx, repoPath, trimmedURL, repoURL, chunksChan)
s.log.Info("scanning github gist comments", "repository", repoPath)
// GitHub Gist URL.
var gistId string
if len(trimmedURL) == 2 {
// https://gist.github.com/<id>
gistId = trimmedURL[1]
} else if len(trimmedURL) == 3 {
// https://gist.github.com/<owner>/<id>
gistId = trimmedURL[2]
} else {
return fmt.Errorf("failed to parse Gist URL: '%s'", repoURL.String())
}
options := &github.ListOptions{
PerPage: defaultPagination,
Page: initialPage,
}
for {
comments, resp, err := s.apiClient.Gists.ListComments(ctx, gistId, options)
if s.handleRateLimit(err, resp) {
break
}
if err != nil {
return err
}
err = s.chunkGistComments(ctx, repoURL.String(), comments, chunksChan)
if err != nil {
return err
}
options.Page++
if len(comments) < options.PerPage {
break
}
}
}
return s.processRepoComments(ctx, repoPath, trimmedURL, repoURL, chunksChan)
}
func (s *Source) processGistComments(ctx context.Context, repoPath string, trimmedURL []string, repoURL *url.URL, chunksChan chan *sources.Chunk) error {
s.log.Info("scanning github gist comments", "repository", repoPath)
// GitHub Gist URL.
gistID, err := extractGistID(trimmedURL)
if err != nil {
return err
}
options := &github.ListOptions{
PerPage: defaultPagination,
Page: initialPage,
}
for {
comments, resp, err := s.apiClient.Gists.ListComments(ctx, gistID, options)
if s.handleRateLimit(err, resp) {
break
}
if err != nil {
return err
}
if err = s.chunkGistComments(ctx, repoURL.String(), comments, chunksChan); err != nil {
return err
}
options.Page++
if len(comments) < options.PerPage {
break
}
}
return nil
}
func extractGistID(url []string) (string, error) {
if len(url) < 2 || len(url) > 3 {
return "", fmt.Errorf("failed to parse Gist URL: length of trimmedURL should be 2 or 3")
}
return url[len(url)-1], nil
}
// Note: these can't be consts because the address is needed when using with the GitHub library.
var (
// sortType defines the criteria for sorting comments.
-19
View File
@@ -743,22 +743,3 @@ func TestProcessRepoComments(t *testing.T) {
})
}
}
func TestGetGistID(t *testing.T) {
tests := []struct {
trimmedURL []string
expected string
err bool
}{
{[]string{"https://gist.github.com", "12345"}, "12345", false},
{[]string{"https://gist.github.com", "owner", "12345"}, "12345", false},
{[]string{"https://gist.github.com"}, "", true},
{[]string{"https://gist.github.com", "owner", "12345", "extra"}, "", true},
}
for _, tt := range tests {
got, err := extractGistID(tt.trimmedURL)
assert.Equal(t, tt.err, err != nil)
assert.Equal(t, tt.expected, got)
}
}
-42
View File
@@ -1,42 +0,0 @@
package github
import (
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/trufflesecurity/trufflehog/v3/pkg/common"
)
var (
githubNumRateLimitEncountered = promauto.NewGaugeVec(prometheus.GaugeOpts{
Namespace: common.MetricsNamespace,
Subsystem: common.MetricsSubsystem,
Name: "github_num_rate_limit_encountered",
Help: "Total number of times Github Rate Limit was encountered",
},
[]string{"source_name"})
githubSecondsSpentRateLimited = promauto.NewGaugeVec(prometheus.GaugeOpts{
Namespace: common.MetricsNamespace,
Subsystem: common.MetricsSubsystem,
Name: "github_seconds_spent_rate_limited",
Help: "Total number of seconds spent idle due to GitHub rate limits.",
},
[]string{"source_name"})
githubReposEnumerated = promauto.NewGaugeVec(prometheus.GaugeOpts{
Namespace: common.MetricsNamespace,
Subsystem: common.MetricsSubsystem,
Name: "github_repos_enumerated",
Help: "Total number of GitHub repositories enumerated.",
},
[]string{"source_name"})
githubReposScanned = promauto.NewGaugeVec(prometheus.GaugeOpts{
Namespace: common.MetricsNamespace,
Subsystem: common.MetricsSubsystem,
Name: "github_repos_scanned",
Help: "Total number of GitHub repositories scanned.",
},
[]string{"source_name"})
)
+1 -5
View File
@@ -52,7 +52,7 @@ func TestSource_Chunks(t *testing.T) {
Secret: s3secret,
},
},
Buckets: []string{"truffletestbucket-s3-tests"},
Buckets: []string{"thog-tmp-test"},
},
},
wantErr: false,
@@ -77,10 +77,7 @@ func TestSource_Chunks(t *testing.T) {
return
}
chunksCh := make(chan *sources.Chunk)
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
err = s.Chunks(ctx, chunksCh)
if (err != nil) != tt.wantErr {
t.Errorf("Source.Chunks() error = %v, wantErr %v", err, tt.wantErr)
@@ -93,7 +90,6 @@ func TestSource_Chunks(t *testing.T) {
if diff := pretty.Compare(gotChunk.Data, wantData); diff != "" {
t.Errorf("%s: Source.Chunks() diff: (-got +want)\n%s", tt.name, diff)
}
wg.Wait()
assert.Equal(t, "", s.GetProgress().EncodedResumeInfo)
assert.Equal(t, int64(100), s.GetProgress().PercentComplete)
})
+3 -8
View File
@@ -6,11 +6,10 @@ import (
"sync/atomic"
"time"
"golang.org/x/sync/errgroup"
"github.com/trufflesecurity/trufflehog/v3/pkg/common"
"github.com/trufflesecurity/trufflehog/v3/pkg/context"
"github.com/trufflesecurity/trufflehog/v3/pkg/pb/sourcespb"
"golang.org/x/sync/errgroup"
)
// handle uniquely identifies a Source given to the manager to manage. If the
@@ -20,7 +19,7 @@ type handle int64
// SourceInitFunc is a function that takes a source and job ID and returns an
// initialized Source.
type SourceInitFunc func(ctx context.Context, jobID, sourceID int64) (Source, error)
type SourceInitFunc func(ctx context.Context, sourceID int64, jobID int64) (Source, error)
// sourceInfo is an aggregate struct to store source information provided on
// initialization.
@@ -229,7 +228,7 @@ func (s *SourceManager) run(ctx context.Context, handle handle, jobID int64, rep
report.ReportError(Fatal{err})
return Fatal{err}
}
source, err := sourceInfo.initFunc(ctx, jobID, int64(handle))
source, err := sourceInfo.initFunc(ctx, int64(handle), jobID)
if err != nil {
report.ReportError(Fatal{err})
return Fatal{err}
@@ -256,7 +255,6 @@ func (s *SourceManager) runWithoutUnits(ctx context.Context, handle handle, sour
go func() {
defer wg.Done()
for chunk := range ch {
chunk.JobID = source.JobID()
report.ReportChunk(nil, chunk)
s.outputChunks <- chunk
}
@@ -336,9 +334,6 @@ func (s *SourceManager) runWithUnits(ctx context.Context, handle handle, source
defer wg.Done()
defer func() { report.EndUnitChunking(unit, time.Now()) }()
for chunk := range chunkReporter.chunkCh {
if src, ok := source.(Source); ok {
chunk.JobID = src.JobID()
}
s.outputChunks <- chunk
}
}()
-39
View File
@@ -245,42 +245,3 @@ func TestSourceManagerContextCancelled(t *testing.T) {
report := ref.Snapshot()
assert.Error(t, report.FatalError())
}
type DummyAPI struct {
registerSource func(context.Context, string, sourcespb.SourceType) (int64, error)
getJobID func(context.Context, int64) (int64, error)
}
func (api DummyAPI) RegisterSource(ctx context.Context, name string, kind sourcespb.SourceType) (int64, error) {
return api.registerSource(ctx, name, kind)
}
func (api DummyAPI) GetJobID(ctx context.Context, id int64) (int64, error) {
return api.getJobID(ctx, id)
}
func TestSourceManagerJobAndSourceIDs(t *testing.T) {
mgr := NewManager(WithAPI(DummyAPI{
registerSource: func(context.Context, string, sourcespb.SourceType) (int64, error) {
return 1337, nil
},
getJobID: func(context.Context, int64) (int64, error) {
return 9001, nil
},
}))
var (
initializedJobID int64
initializedSourceID int64
)
handle, err := mgr.Enroll(context.Background(), "dummy", 1337,
func(ctx context.Context, jobID, sourceID int64) (Source, error) {
initializedJobID = jobID
initializedSourceID = sourceID
return nil, fmt.Errorf("ignore")
})
assert.NoError(t, err)
_, _ = mgr.Run(context.Background(), handle)
assert.Equal(t, int64(1337), initializedSourceID)
assert.Equal(t, int64(9001), initializedJobID)
}
+1 -3
View File
@@ -17,8 +17,6 @@ type Chunk struct {
SourceName string
// SourceID is the ID of the source that the Chunk originated from.
SourceID int64
// JobID is the ID of the job that the Chunk originated from.
JobID int64
// SourceType is the type of Source that produced the chunk.
SourceType sourcespb.SourceType
// SourceMetadata holds the context of where the Chunk was found.
@@ -250,7 +248,7 @@ type Progress struct {
// Validator is an interface for validating a source. Sources can optionally implement this interface to validate
// their configuration.
type Validator interface {
Validate(ctx context.Context) []error
Validate() []error
}
// SetProgressComplete sets job progress information for a running job based on the highest level objects in the source.
+1 -1
View File
@@ -60,7 +60,7 @@ func NewSyslog(sourceType sourcespb.SourceType, jobID, sourceID int64, sourceNam
}
// Validate validates the configuration of the source.
func (s *Source) Validate(ctx context.Context) []error {
func (s *Source) Validate() []error {
var errors []error
if s.conn.TlsCert != nilString || s.conn.TlsKey != nilString {
+7 -7
View File
@@ -19,16 +19,14 @@ import (
"github.com/trufflesecurity/trufflehog/v3/pkg/version"
)
func Fetcher(version string) fetcher.Interface {
return &OSS{
CurrentVersion: version,
}
func Fetcher(tui bool) fetcher.Interface {
return &OSS{TUI: tui}
}
type OSS struct {
Interval time.Duration
CurrentVersion string
Updated bool
Interval time.Duration
TUI bool
Updated bool
}
// Init validates the provided config
@@ -43,6 +41,7 @@ type FormData struct {
OS string
Arch string
CurrentVersion string
TUI bool
Timezone string
Binary string
}
@@ -59,6 +58,7 @@ func (g *OSS) Fetch() (io.Reader, error) {
OS: runtime.GOOS,
Arch: runtime.GOARCH,
CurrentVersion: version.BuildVersion,
TUI: g.TUI,
Timezone: zone,
Binary: "trufflehog",
}