-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
travisci.go
225 lines (193 loc) · 5.96 KB
/
travisci.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
package travisci
import (
"fmt"
"strconv"
"github.com/go-errors/errors"
"github.com/shuheiktgw/go-travis"
"golang.org/x/sync/errgroup"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/known/anypb"
"github.com/trufflesecurity/trufflehog/v3/pkg/common"
"github.com/trufflesecurity/trufflehog/v3/pkg/context"
"github.com/trufflesecurity/trufflehog/v3/pkg/pb/source_metadatapb"
"github.com/trufflesecurity/trufflehog/v3/pkg/pb/sourcespb"
"github.com/trufflesecurity/trufflehog/v3/pkg/sources"
)
const (
SourceType = sourcespb.SourceType_SOURCE_TYPE_TRAVISCI
baseURL = "https://api.travis-ci.com/"
pageSize = 100
)
type Source struct {
name string
sourceId sources.SourceID
jobId sources.JobID
verify bool
jobPool *errgroup.Group
sources.Progress
client *travis.Client
sources.CommonSourceUnitUnmarshaller
returnAfterFirstChunk bool
}
// Ensure the Source satisfies the interfaces at compile time.
var _ sources.Source = (*Source)(nil)
var _ sources.SourceUnitUnmarshaller = (*Source)(nil)
// Type returns the type of source.
// It is used for matching source types in configuration and job input.
func (s *Source) Type() sourcespb.SourceType {
return SourceType
}
func (s *Source) SourceID() sources.SourceID {
return s.sourceId
}
func (s *Source) JobID() sources.JobID {
return s.jobId
}
// Init returns an initialized TravisCI source.
func (s *Source) Init(ctx context.Context, name string, jobId sources.JobID, sourceId sources.SourceID, verify bool, connection *anypb.Any, concurrency int) error {
s.name = name
s.sourceId = sourceId
s.jobId = jobId
s.verify = verify
s.jobPool = &errgroup.Group{}
s.jobPool.SetLimit(concurrency)
var conn sourcespb.TravisCI
if err := anypb.UnmarshalTo(connection, &conn, proto.UnmarshalOptions{}); err != nil {
return errors.WrapPrefix(err, "error unmarshalling connection", 0)
}
switch conn.Credential.(type) {
case *sourcespb.TravisCI_Token:
if conn.GetToken() == "" {
return errors.New("token is empty")
}
s.client = travis.NewClient(baseURL, conn.GetToken())
s.client.HTTPClient = common.RetryableHTTPClientTimeout(3)
user, _, err := s.client.User.Current(ctx, nil)
if err != nil {
return errors.WrapPrefix(err, "error getting testing travis client", 0)
}
ctx.Logger().V(2).Info("authenticated to Travis CI with user", "username", user.Login)
default:
return errors.New("credential type not implemented for Travis CI")
}
return nil
}
func (s *Source) Enumerate(ctx context.Context, reporter sources.UnitReporter) error {
for repoPage := 0; ; repoPage++ {
repositories, _, err := s.client.Repositories.List(ctx, &travis.RepositoriesOption{
Limit: pageSize,
Offset: repoPage * pageSize,
})
if err != nil {
if repoPage == 0 {
return fmt.Errorf("error listing repositories: %w", err)
}
err = reporter.UnitErr(ctx, err)
if err != nil {
return fmt.Errorf("error reporting error: %w", err)
}
}
if len(repositories) == 0 {
break
}
for _, repo := range repositories {
err = reporter.UnitOk(ctx, sources.CommonSourceUnit{
ID: strconv.Itoa(int(*repo.Id)),
Kind: "repo",
})
if err != nil {
return fmt.Errorf("error reporting unit: %w", err)
}
ctx.Logger().V(2).Info("enumerated repository", "id", repo.Id, "name", repo.Name)
}
}
return nil
}
// ChunkUnit implements SourceUnitChunker interface.
func (s *Source) ChunkUnit(ctx context.Context, unit sources.SourceUnit, reporter sources.ChunkReporter) error {
repoURL, _ := unit.SourceUnitID()
repo, _, err := s.client.Repositories.Find(ctx, repoURL, nil)
if err != nil {
return fmt.Errorf("error finding repository: %w", err)
}
logger := ctx.Logger().WithValues("repo", *repo.Name)
logger.V(2).Info("scanning repository")
// Counts continuous errors from ListByRepoSlug. Used to quit early in
// case the API always returns an error.
var buildPageErrs int
for buildPage := 0; ; buildPage++ {
builds, _, err := s.client.Builds.ListByRepoSlug(ctx, *repo.Slug, &travis.BuildsByRepoOption{
Limit: pageSize,
Offset: buildPage * pageSize,
})
if err != nil {
if err := reporter.ChunkErr(ctx, err); err != nil {
return err
}
buildPageErrs++
if buildPageErrs >= 5 {
return fmt.Errorf("encountered too many errors listing builds, aborting")
}
continue
}
// Reset the page error counter.
buildPageErrs = 0
if len(builds) == 0 {
break
}
for _, build := range builds {
jobs, _, err := s.client.Jobs.ListByBuild(ctx, *build.Id)
if err != nil {
if err := reporter.ChunkErr(ctx, err); err != nil {
return err
}
continue
}
if len(jobs) == 0 {
break
}
for _, job := range jobs {
log, _, err := s.client.Logs.FindByJobId(ctx, *job.Id)
if err != nil {
if err := reporter.ChunkErr(ctx, err); err != nil {
return err
}
continue
}
logger.V(3).Info("scanning job", "id", *job.Id, "number", *job.Number)
chunk := sources.Chunk{
SourceType: s.Type(),
SourceName: s.name,
SourceID: s.SourceID(),
JobID: s.JobID(),
Data: []byte(*log.Content),
SourceMetadata: &source_metadatapb.MetaData{
Data: &source_metadatapb.MetaData_TravisCI{
TravisCI: &source_metadatapb.TravisCI{
Username: *job.Owner.Login,
Repository: *repo.Name,
BuildNumber: *build.Number,
JobNumber: *job.Number,
Link: fmt.Sprintf("https://app.travis-ci.com/github/%s/%s/jobs/%d", *job.Owner.Login, *repo.Name, *job.Id),
Public: !*repo.Private,
},
},
},
Verify: s.verify,
}
if err := reporter.ChunkOk(ctx, chunk); err != nil {
return err
}
if s.returnAfterFirstChunk {
return nil
}
}
}
}
return nil
}
// Chunks emits chunks of bytes over a channel.
// It's a no-op because we've implemented the SourceUnitChunker interface instead.
func (s *Source) Chunks(ctx context.Context, chunksChan chan *sources.Chunk, _ ...sources.ChunkingTarget) error {
return nil
}