-
Notifications
You must be signed in to change notification settings - Fork 2
/
file.go
205 lines (176 loc) · 5.78 KB
/
file.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
package nightfall
import (
"context"
"io"
"net/http"
"sync"
"time"
"github.com/google/uuid"
)
// ScanPolicy contains configuration that describes how to scan a file. Since the file is scanned asynchronously,
// the results from the scan are delivered to the provided webhook URL. The scan configuration may contain both
// inline detection rule definitions and UUID's referring to existing detection rules (up to 10 of each).
type ScanPolicy struct {
WebhookURL string `json:"webhookURL"` // Deprecated: use AlertConfig instead
DetectionRules []DetectionRule `json:"detectionRules"`
DetectionRuleUUIDs []string `json:"detectionRuleUUIDs"`
AlertConfig *AlertConfig `json:"alertConfig"`
}
// ScanFileRequest represents a request to scan a file that was uploaded via the Nightfall API. Exactly one of
// PolicyUUID or Policy should be provided.
type ScanFileRequest struct {
PolicyUUID *string `json:"policyUUID"`
Policy *ScanPolicy `json:"policy"`
RequestMetadata string `json:"requestMetadata"`
Content io.Reader `json:"-"`
ContentSizeBytes int64 `json:"-"`
Timeout time.Duration `json:"-"`
}
// ScanFileResponse is the object returned by the Nightfall API when an (asynchronous) file scan request
// was successfully triggered.
type ScanFileResponse struct {
ID string `json:"id"`
Message string `json:"message"`
}
type fileUploadResponse struct {
ID uuid.UUID `json:"id"`
FileSizeBytes int64 `json:"fileSizeBytes"`
ChunkSize int64 `json:"chunkSize"`
MIMEType string `json:"mimeType"`
}
type fileUploadRequest struct {
FileSizeBytes int64 `json:"fileSizeBytes"`
}
// ScanFile is a convenience method that abstracts the details of the multi-step file upload and scan process.
// Calling this method for a given file is equivalent to (1) manually initializing a file upload session,
// (2) uploading all chunks of the file, (3) completing the upload, and (4) triggering a scan of the file.
//
// The maximum allowed ContentSizeBytes is dependent on the terms of your current
// Nightfall usage plan agreement; check the Nightfall dashboard for more details.
//
// This method consumes the provided reader, but it does not close it; closing remains
// the caller's responsibility.
func (c *Client) ScanFile(ctx context.Context, request *ScanFileRequest) (*ScanFileResponse, error) {
var cancel context.CancelFunc
if request.Timeout > 0 {
ctx, cancel = context.WithTimeout(ctx, request.Timeout)
} else {
ctx, cancel = context.WithCancel(ctx)
}
defer cancel()
fileUpload, err := c.initFileUpload(ctx, &fileUploadRequest{FileSizeBytes: request.ContentSizeBytes})
if err != nil {
return nil, err
}
err = c.doChunkedUpload(ctx, fileUpload, request.Content)
if err != nil {
return nil, err
}
err = c.completeFileUpload(ctx, fileUpload.ID)
if err != nil {
return nil, err
}
return c.scanUploadedFile(ctx, request, fileUpload.ID)
}
func (c *Client) initFileUpload(ctx context.Context, request *fileUploadRequest) (*fileUploadResponse, error) {
body, err := encodeBodyAsJSON(request)
if err != nil {
return nil, err
}
reqParams := requestParams{
method: http.MethodPost,
url: c.baseURL + "v3/upload",
body: body,
headers: c.defaultHeaders(),
}
uploadResponse := &fileUploadResponse{}
err = c.do(ctx, reqParams, uploadResponse)
if err != nil {
return nil, err
}
return uploadResponse, nil
}
func (c *Client) doChunkedUpload(ctx context.Context, fileUpload *fileUploadResponse, content io.Reader) error {
errChan := make(chan error, 1)
wg := &sync.WaitGroup{}
concurrencyChan := make(chan struct{}, c.fileUploadConcurrency)
uploadCtx, cancel := context.WithCancel(ctx)
defer cancel()
upload:
for offset := int64(0); offset < fileUpload.FileSizeBytes; offset += fileUpload.ChunkSize {
// Check if we are at max upload concurrency limit and block if we are
concurrencyChan <- struct{}{}
// Check if there were any errors from uploading previous chunks, and break if there were
select {
case <-uploadCtx.Done():
break upload
default:
}
buf := make([]byte, fileUpload.ChunkSize)
bytesRead, err := content.Read(buf)
if err == io.EOF {
break
} else if err != nil {
return err
}
if int64(bytesRead) < fileUpload.ChunkSize {
buf = buf[:bytesRead]
}
wg.Add(1)
go func(o int64, data []byte) {
defer func() {
wg.Done()
<-concurrencyChan
}()
reqParams := requestParams{
method: http.MethodPatch,
url: c.baseURL + "v3/upload/" + fileUpload.ID.String(),
body: data,
headers: c.chunkedUploadHeaders(o),
}
err = c.do(uploadCtx, reqParams, nil)
if err != nil {
// If error channel is full already just discard this error, first error is most likely the most useful one anyways
select {
case errChan <- err:
default:
}
cancel()
return
}
}(offset, buf)
}
wg.Wait()
close(errChan)
if err := <-errChan; err != nil {
return err
}
return nil
}
func (c *Client) completeFileUpload(ctx context.Context, fileUUID uuid.UUID) error {
reqParams := requestParams{
method: http.MethodPost,
url: c.baseURL + "v3/upload/" + fileUUID.String() + "/finish",
body: nil,
headers: c.defaultHeaders(),
}
return c.do(ctx, reqParams, nil)
}
func (c *Client) scanUploadedFile(ctx context.Context, request *ScanFileRequest, fileUUID uuid.UUID) (*ScanFileResponse, error) {
body, err := encodeBodyAsJSON(request)
if err != nil {
return nil, err
}
reqParams := requestParams{
method: http.MethodPost,
url: c.baseURL + "v3/upload/" + fileUUID.String() + "/scan",
body: body,
headers: c.defaultHeaders(),
}
scanResponse := &ScanFileResponse{}
err = c.do(ctx, reqParams, scanResponse)
if err != nil {
return nil, err
}
return scanResponse, nil
}