-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
305 lines (270 loc) · 8.21 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
package main
import (
"crypto/hmac"
"crypto/sha1"
"encoding/hex"
"errors"
"fmt"
"log"
"math/rand"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"time"
)
const (
port = 19165
screenshotPath = "/api/spectura/v0/screenshot"
infoPath = "/api/spectura/v0/info"
)
var (
autoRefreshAfter time.Duration
bgRateLimitTime time.Duration
cacheTTL time.Duration
decapURL string
adminToken string
ignoreBackgroundRequests bool
maxImageSize int
refreshTaskDelay time.Duration
scheduleInterval time.Duration
signingKey string
signingSecret string
signingUniqueName string
useSignatures bool
webhookURL string
webhookAuthHeader string
)
var cache Cache
func main() {
rand.Seed(time.Now().UnixNano())
cacheTTLString, _ := getenv("CACHE_TTL", "48h")
var err error
cacheTTL, err = time.ParseDuration(cacheTTLString)
if err != nil {
log.Fatalf(`CACHE_TTL must be a valid duration such as "12h": %s\n`, err)
}
scheduleIntervalString, _ := getenv("SCHEDULE_INTERVAL", "5m")
scheduleInterval, err = time.ParseDuration(scheduleIntervalString)
if err != nil {
log.Fatalf(`SCHEDULE_INTERVAL must be a valid duration such as "12h": %s\n`, err)
}
autoRefreshAfterString, _ := getenv("AUTO_REFRESH_AFTER", "6h")
autoRefreshAfter, err = time.ParseDuration(autoRefreshAfterString)
if err != nil {
log.Fatalf(`AUTO_REFRESH_AFTER must be a valid duration such as "12h": %s\n`, err)
}
refreshTaskDelayString, _ := getenv("REFRESH_TASK_DELAY", "5s")
refreshTaskDelay, err = time.ParseDuration(refreshTaskDelayString)
if err != nil {
log.Fatalf(`REFRESH_TASK_DELAY must be a valid duration such as "12h": %s\n`, err)
}
bgRateLimitTimeString, _ := getenv("BG_RATE_LIMIT_TIME", "3h")
bgRateLimitTime, err = time.ParseDuration(bgRateLimitTimeString)
if err != nil {
log.Fatalf(`BG_RATE_LIMIT_TIME must be a valid duration such as "3h": %s\n`, err)
}
maxImageSizeString, _ := getenv("MAX_IMAGE_SIZE_MIB", "20")
maxImageSizeMiB, err := strconv.Atoi(maxImageSizeString)
if err != nil {
log.Fatalf("MAX_IMAGE_SIZE_MIB must be a number: %s \n", err)
}
const bytesInMiB = 1 << 20
maxImageSize = bytesInMiB * maxImageSizeMiB
decapURL, err = getenv("DECAP_URL", "http://localhost:4531")
if err != nil {
log.Fatal(err)
}
adminToken, _ = getenv("ADMIN_TOKEN", "")
ignoreBackgroundRequestsString, _ := getenv("IGNORE_BACKGROUND_REQUESTS", "false")
ignoreBackgroundRequests = ignoreBackgroundRequestsString == "true"
useSignaturesString, _ := getenv("USE_SIGNATURES", "true")
if useSignaturesString == "true" {
useSignatures = true
signingSecret, err = getenv("SIGNING_SECRET")
if err != nil {
log.Fatalf("%s (alternatively set USE_SIGNATURES=false)", err)
}
signingKey, err = getenv("SIGNING_KEY")
if err != nil {
log.Fatalf("%s (alternatively set USE_SIGNATURES=false)", err)
}
signingUniqueName, _ = getenv("SIGNING_UNIQUE_NAME", "jix_spectura")
} else {
useSignatures = false
}
webhookURL, _ = getenv("WEBHOOK_URL")
webhookAuthHeader, _ = getenv("WEBHOOK_AUTHORIZATION_HEADER")
cache.Init()
if err = loadImageConf(); err != nil {
log.Fatalf(`Couldn't load image configuration from "%s": %s`, imageConfPath, err)
}
http.HandleFunc("/", http.NotFound)
http.Handle(screenshotPath, http.HandlerFunc(screenshotHandler))
http.Handle(infoPath, http.HandlerFunc(infoHandler))
fmt.Fprintf(os.Stderr,
"%s spectura is listening on http://localhost:%d%s\n",
time.Now().Format("[15:04:05]"), port, screenshotPath,
)
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", port), nil))
}
func getenv(key string, fallback ...string) (string, error) {
value := os.Getenv(key)
if value != "" {
return value, nil
}
if len(fallback) > 1 {
return "", fmt.Errorf("getenv only takes 1 or 2 parameters")
}
if len(fallback) == 1 {
return fallback[0], nil
}
return "", fmt.Errorf("missing environment variable %s", key)
}
// Check a JIX::UrlSignature hash signature
func checkSignature(url string, signature string, expire string) bool {
h := hmac.New(sha1.New, []byte(signingKey))
h.Write([]byte(signingUniqueName + ":" + url + expire + signingSecret))
signatureShouldBe := hex.EncodeToString(h.Sum(nil))
return signature == signatureShouldBe
}
func screenshotHandler(w http.ResponseWriter, req *http.Request) {
query := req.URL.Query()
rawURL := query.Get("url")
if rawURL == "" {
http.Error(w, `Query param "url" must be present`, http.StatusBadRequest)
return
}
signature := query.Get("s")
if useSignatures && signature == "" {
http.Error(w, `Query param "s" must be present`, http.StatusBadRequest)
return
}
expireRaw := query.Get("expire")
var expire int64
// Conditions where expire is left as 0, are handled after signature check.
if expireRaw != "" {
var err error
expire, err = strconv.ParseInt(expireRaw, 10, 64)
if err != nil {
http.Error(w, `Query param "expire" must be a number`, http.StatusBadRequest)
return
}
}
targetURL, err := url.Parse(rawURL)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if useSignatures && !checkSignature(targetURL.String(), signature, expireRaw) {
http.Error(w, "Signature check failed", http.StatusBadRequest)
return
}
if expire == 0 || time.Now().After(time.Unix(expire, 0)) {
// Redirect to fallback image
http.Redirect(w, req, fallbackImageURL, http.StatusFound)
return
}
if query.Get("nocrop") != "" && !useSignatures {
entry := CacheEntry{URL: targetURL}
fmt.Fprintf(os.Stderr, "Cache-miss (nocrop): %s\n", entry.URL)
err = entry.fetchAndCropImage(false, true)
if err != nil {
msg := fmt.Sprintf("nocrop fail: %s", err)
http.Error(w, msg, http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "image/png")
w.Write(entry.Image)
return
}
entry := cache.Read(targetURL.String())
if query.Get("bg") != "" {
if ignoreBackgroundRequests {
w.Write([]byte("Ignored"))
return
}
if entry.IsEmpty() {
entry.Expire = time.Unix(expire, 0)
entry.Signature = signature
entry.URL = targetURL
} else {
admin := query.Get("token") != "" && query.Get("token") == adminToken
elapsed := time.Since(entry.LastRefreshAttempt)
if !admin && elapsed < bgRateLimitTime {
msg := fmt.Sprintf("%s since last background request", elapsed)
http.Error(w, msg, http.StatusTooManyRequests)
return
}
}
// Create cache entry / update timestamp, so repeated background queries
// can be rejected while this query is queued.
cache.WriteMetadata(entry)
go cache.runRefreshTask(entry)
fmt.Fprint(w, "Success, refresh is now in progress. This can take up to 30 seconds.\n")
return
}
if entry.IsEmpty() {
entry = CacheEntry{
Expire: time.Unix(expire, 0),
LastFetched: time.Now(),
Provenance: newProvenance(req),
Signature: signature,
URL: targetURL,
}
fmt.Fprintf(os.Stderr, "Cache miss: %s\n", entry.URL)
err = entry.fetchAndCropImage(false, false)
switch {
case err == nil:
cache.Write(entry)
case errors.Is(err, croppingError) || errors.Is(err, decapInternalError):
cache.WriteMetadata(entry)
entry = cache.Read(entry.URL.String())
default:
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
go cache.runRefreshTask(entry)
} else if !strings.Contains(req.Referer(), infoPath) {
fmt.Fprintf(os.Stderr, "Cache hit: %s\n", entry.URL)
if entry.Provenance.when.IsZero() {
entry.Provenance = newProvenance(req)
}
entry.LastFetched = time.Now()
cache.WriteMetadata(entry)
}
w.Header().Set("Content-Type", "image/png")
w.Write(entry.Image)
}
type Provenance struct {
addr string
referer string
userAgent string
when time.Time
}
func newProvenance(req *http.Request) Provenance {
return Provenance{
addr: req.RemoteAddr,
referer: req.Referer(),
userAgent: req.UserAgent(),
when: time.Now(),
}
}
func (p Provenance) String() string {
if p.when.IsZero() {
return p.when.Format(time.UnixDate)
}
s := fmt.Sprintf(
"%s | %s | %s | %s",
p.when.Format(time.UnixDate),
p.addr,
p.referer,
p.userAgent,
)
const max = 150
if len(s) > max {
return fmt.Sprintf("%*s...", max-3, s)
}
return s
}