-
Notifications
You must be signed in to change notification settings - Fork 168
/
main.go
330 lines (276 loc) · 12.7 KB
/
main.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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package main
import (
"archive/zip"
"bytes"
"context"
"fmt"
"html"
"io/ioutil"
"net/http"
"os"
"os/signal"
"path/filepath"
"strconv"
"strings"
"syscall"
"golang.org/x/sync/errgroup"
)
type Args struct {
UNZIP_AT string
PORT string
API_KEY string
ROOT_PATH string
}
var ENV_VARS = Args{
UNZIP_AT: "DEV_DEPLOYMENT__UPLOAD_SERVICE_EXTRACT_TO_DIR",
PORT: "DEV_DEPLOYMENT__UPLOAD_SERVICE_PORT",
API_KEY: "DEV_DEPLOYMENT__UPLOAD_SERVICE_API_KEY",
ROOT_PATH: "DEV_DEPLOYMENT__UPLOAD_SERVICE_ROOT_PATH",
}
var GLOBAL__UPLOAD_CAPTURED = false
var MAX_UPLOADED_FILE_SIZE_IN_BYTES int64 = 200 << 20 // 200 MiB
var LOG_PREFIX = "[dev-deployment-upload-service] "
func main() {
unzipAtArgString := os.Getenv(ENV_VARS.UNZIP_AT)
portArgString := os.Getenv(ENV_VARS.PORT)
apiKeyArgString := os.Getenv(ENV_VARS.API_KEY)
rootPathArgString := os.Getenv(ENV_VARS.ROOT_PATH)
// Validate arguments
if len(os.Args) > 1 {
fmt.Fprintf(os.Stderr, LOG_PREFIX+"❌ ERROR: No positional arguments allowed.\n")
fmt.Fprintf(os.Stderr, LOG_PREFIX+"\n")
printUsage()
os.Exit(1)
} else if len(unzipAtArgString) <= 0 || len(portArgString) <= 0 || len(apiKeyArgString) <= 0 {
fmt.Fprintf(os.Stderr, LOG_PREFIX+"❌ ERROR: Missing env var arguments.\n")
fmt.Fprintf(os.Stderr, LOG_PREFIX+"\n")
printUsage()
os.Exit(1)
}
// Validate --port
port, err := strconv.Atoi(portArgString)
if err != nil {
fmt.Fprintf(os.Stderr, LOG_PREFIX+"❌ ERROR: '%s' is not a valid port number.\n", portArgString)
os.Exit(1)
}
unzipAtPath := unzipAtArgString
// Validate --unzip-at
if _, err := os.Stat(unzipAtArgString); err == nil {
fmt.Fprintf(os.Stdout, LOG_PREFIX+"✅ Found directory '%s'.\n", unzipAtArgString)
} else if err := os.MkdirAll(unzipAtArgString, os.ModePerm); err != nil { // os.ModePerm == chmod 777
fmt.Fprintf(os.Stderr, LOG_PREFIX+"❌ ERROR: Creating directory '%s' failed:\n", unzipAtArgString)
fmt.Fprintf(os.Stderr, LOG_PREFIX+"❌ ERROR: %+v\n", err)
os.Exit(1)
} else {
fmt.Fprintf(os.Stdout, LOG_PREFIX+"✅ Created directory '%s'.\n", unzipAtArgString)
}
// All validations passed. Start the program.
httpServerBgContext, cancelHttpServerBgContext := context.WithCancel(context.Background())
httpServerBgGroup, httpServerBgGroupContext := errgroup.WithContext(httpServerBgContext)
shutdownWithErrorOnFileUpload := func(filename string) {
httpServerBgGroup.Go(func() error { return fmt.Errorf("uploading '%s' failed", filename) })
}
rootPath := rootPathArgString
uploadStatusPath := "/upload-status"
if len(rootPathArgString) > 1 {
uploadStatusPath = fmt.Sprintf("/%s/upload-status", rootPath)
}
http.HandleFunc(uploadStatusPath, func(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
w.WriteHeader(http.StatusOK)
w.Write([]byte("READY"))
})
uploadPath := "/upload"
if len(rootPathArgString) > 1 {
uploadPath = fmt.Sprintf("/%s/upload", rootPath)
}
http.HandleFunc(uploadPath, func(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
if req.Method == "OPTIONS" {
w.WriteHeader(http.StatusNoContent)
return
}
apiKey := req.URL.Query().Get("apiKey")
if apiKey != apiKeyArgString {
fmt.Fprintf(os.Stdout, LOG_PREFIX+"⚠️ Attempted to upload with the wrong API Key: '%s'.\n", apiKey)
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte("401: Unauthorized."))
return
}
if GLOBAL__UPLOAD_CAPTURED {
fmt.Fprintf(os.Stdout, LOG_PREFIX+"⚠️ Upload arrived, but another arrived earlier. Server should be in the process of gracefully shutting down.\n")
w.WriteHeader(http.StatusConflict)
w.Write([]byte("409: Another upload arrived first. Can't accept this one. Server is in the process of shutting down."))
return
}
GLOBAL__UPLOAD_CAPTURED = true
fmt.Fprintf(os.Stdout, LOG_PREFIX+"ℹ️ Upload arrived...\n")
req.ParseMultipartForm(MAX_UPLOADED_FILE_SIZE_IN_BYTES)
// FormFile returns the first file for the given key `myFile`
// it also returns the FileHeader so we can get the Filename,
// the Header and the size of the file
uploadedFile, handler, err := req.FormFile("myFile") // TODO: Is there a way to not need this?
if err != nil {
fmt.Fprintf(os.Stderr, LOG_PREFIX+"❌ ERROR: Reading uploaded file failed:\n")
fmt.Fprintf(os.Stderr, LOG_PREFIX+"❌ ERROR: %+v\n", err)
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("500: Reading uploaded file failed."))
shutdownWithErrorOnFileUpload(handler.Filename)
return
}
defer uploadedFile.Close()
fmt.Fprintf(os.Stdout, LOG_PREFIX+"ℹ️ Uploaded File: %+v\n", handler.Filename)
fmt.Fprintf(os.Stdout, LOG_PREFIX+"ℹ️ File Size: %+v\n", handler.Size)
fmt.Fprintf(os.Stdout, LOG_PREFIX+"ℹ️ MIME Header: %+v\n", handler.Header)
// Read all the contents of the uploaded file into a byte array
uploadedZipBytes, err := ioutil.ReadAll(uploadedFile)
if err != nil {
fmt.Fprintf(os.Stderr, LOG_PREFIX+"❌ ERROR: Reading bytes of uploaded zip file failed:\n")
fmt.Fprintf(os.Stderr, LOG_PREFIX+"❌ ERROR: %+v\n", err)
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("500: Reading bytes of uploaded zip file failed."))
shutdownWithErrorOnFileUpload(handler.Filename)
return
}
// Extract zip contents to `extractedZippedFilePath`
zipReader, err := zip.NewReader(bytes.NewReader(uploadedZipBytes), int64(len(uploadedZipBytes)))
if err != nil {
fmt.Fprintf(os.Stderr, LOG_PREFIX+"❌ ERROR: Creating zip reader failed.\n")
fmt.Fprintf(os.Stderr, LOG_PREFIX+"❌ ERROR: %+v\n", err)
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("500: Creating zip reader failed."))
shutdownWithErrorOnFileUpload(handler.Filename)
return
}
for _, zipFile := range zipReader.File {
unzippedFileBytes, err := readZipFile(zipFile)
if err != nil {
fmt.Fprintf(os.Stderr, LOG_PREFIX+"❌ ERROR: Reading zipped file '%s' failed:\n", zipFile.Name)
fmt.Fprintf(os.Stderr, LOG_PREFIX+"❌ ERROR: %+v\n", err)
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("500: Reading zipped file. " + html.EscapeString(zipFile.Name)))
shutdownWithErrorOnFileUpload(handler.Filename)
return
}
// Check for Zip Slip (directory traversal)
extractedZippedFilePath := filepath.Join(unzipAtPath, zipFile.Name)
if !strings.HasPrefix(extractedZippedFilePath, filepath.Clean(unzipAtPath)+string(os.PathSeparator)) {
fmt.Fprintf(os.Stderr, LOG_PREFIX+"❌ ERROR: Illegal zipped file path '%s'.\n", zipFile.Name)
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("500: Illegal zipped file path. " + html.EscapeString(extractedZippedFilePath)))
shutdownWithErrorOnFileUpload(handler.Filename)
return
}
// Always try and write the dirs where the files are going to be written to.
if err := os.MkdirAll(filepath.Dir(extractedZippedFilePath), os.ModePerm); err != nil { // os.ModePerm == chmod 777
fmt.Fprintf(os.Stderr, LOG_PREFIX+"❌ ERROR: Creating directory '%s' failed:\n", filepath.Dir(extractedZippedFilePath))
fmt.Fprintf(os.Stderr, LOG_PREFIX+"❌ ERROR: %+v\n", err)
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("500: Creating directory failed. " + html.EscapeString(filepath.Dir(extractedZippedFilePath))))
shutdownWithErrorOnFileUpload(handler.Filename)
return
}
// Only write the file if it's not a dir
if !zipFile.FileInfo().IsDir() {
f, err := os.Create(extractedZippedFilePath)
if err != nil {
fmt.Fprintf(os.Stderr, LOG_PREFIX+"❌ ERROR: Creating file '%s' failed:\n", extractedZippedFilePath)
fmt.Fprintf(os.Stderr, LOG_PREFIX+"❌ ERROR: %+v\n", err)
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("500: Creating file failed. " + html.EscapeString(extractedZippedFilePath)))
shutdownWithErrorOnFileUpload(handler.Filename)
return
}
if _, err := f.Write(unzippedFileBytes); err != nil {
fmt.Fprintf(os.Stderr, LOG_PREFIX+"❌ ERROR: Writing file '%s' failed:\n", extractedZippedFilePath)
fmt.Fprintf(os.Stderr, LOG_PREFIX+"❌ ERROR: %+v\n", err)
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("500: Writing file failed. " + html.EscapeString(extractedZippedFilePath)))
shutdownWithErrorOnFileUpload(handler.Filename)
return
}
fmt.Fprintf(os.Stdout, LOG_PREFIX+"✅ Wrote '%s'...\n", extractedZippedFilePath)
defer f.Close()
}
}
// Return that we have successfully uploaded the zip file
w.WriteHeader(http.StatusOK)
w.Write([]byte(fmt.Sprintf("200: Successfully extracted '%s' to '%s'.\n", html.EscapeString(handler.Filename), html.EscapeString(unzipAtPath))))
fmt.Fprintf(os.Stdout, LOG_PREFIX+"✅ Successfully extracted '%s' to '%s'.\n", html.EscapeString(handler.Filename), html.EscapeString(unzipAtPath))
// End the program gracefully.
cancelHttpServerBgContext()
})
httpServer := http.Server{Addr: ":" + portArgString}
// Goroutine for listening for Ctrl + C signal for graceful shutdown.
go func() {
c := make(chan os.Signal, 1) // We need to reserve to buffer size 1, so the notifier are not blocked
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
<-c // Wait for signal to come
fmt.Fprintf(os.Stdout, "\n")
cancelHttpServerBgContext()
}()
// Goroutine for running the HTTP server.
httpServerBgGroup.Go(func() error {
fmt.Fprintf(os.Stdout, LOG_PREFIX+"ℹ️ Starting HTTP server...\n")
fmt.Fprintf(os.Stdout, LOG_PREFIX+"ℹ️ Running at port %d.\n", port)
fmt.Fprintf(os.Stdout, LOG_PREFIX+"ℹ️ The uploaded zip will be extracted to %s.\n", unzipAtPath)
fmt.Fprintf(os.Stdout, LOG_PREFIX+"ℹ️ The root path is set to %s.\n", rootPathArgString)
fmt.Fprintf(os.Stdout, LOG_PREFIX+"ℹ️ Waiting for upload to arrive...\n")
fmt.Fprintf(os.Stdout, LOG_PREFIX+"--------------------------------------------------------\n")
return httpServer.ListenAndServe()
})
// Goroutine for shutting down the HTTP server...
httpServerBgGroup.Go(func() error {
<-httpServerBgGroupContext.Done()
fmt.Fprintf(os.Stdout, LOG_PREFIX+"ℹ️ Shutting down HTTP server...\n")
return httpServer.Shutdown(context.Background()) // Will return `http.ErrServerClosed` is everything goes well.
})
// Waiting until bgGroup finishes, printing errors or not.
if err := httpServerBgGroup.Wait(); err == nil || err == http.ErrServerClosed {
fmt.Fprintf(os.Stdout, LOG_PREFIX+"✅ Shutdown completed successfully.\n")
os.Exit(0)
} else {
fmt.Fprintf(os.Stderr, LOG_PREFIX+"❌ Shutdown complete, but exiting with code 1, as the following error occurred:\n")
fmt.Fprintf(os.Stderr, "%+v\n", err)
os.Exit(1)
}
}
func readZipFile(zf *zip.File) ([]byte, error) {
f, err := zf.Open()
if err != nil {
return nil, err
}
defer f.Close()
return ioutil.ReadAll(f)
}
func printUsage() {
fmt.Fprintf(os.Stderr, LOG_PREFIX+"USAGE: `dev-deployment-upload-service`. Arguments are passed using env vars:\n")
fmt.Fprintf(os.Stderr, LOG_PREFIX+fmt.Sprintf("- %s:\t Required. Where the uploaded zip will be extracted to. If it doesn't exist, it will be created.\n", ENV_VARS.UNZIP_AT))
fmt.Fprintf(os.Stderr, LOG_PREFIX+fmt.Sprintf("- %s:\t\t\t Required. Port where the HTTP Server will run at. The /upload endpoint will be made available.\n", ENV_VARS.PORT))
fmt.Fprintf(os.Stderr, LOG_PREFIX+fmt.Sprintf("- %s:\t\t Required. Allowed API Key used as a queryParam at the /upload endpoint.\n", ENV_VARS.API_KEY))
fmt.Fprintf(os.Stderr, LOG_PREFIX+"\n")
fmt.Fprintf(os.Stderr, LOG_PREFIX+"Example:\n")
fmt.Fprintf(os.Stderr, LOG_PREFIX+"curl -X POST http://localhost:[port]/upload?apiKey=[apiKey]\n") // TODO: This is not right..
}