-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
141 lines (121 loc) · 3.66 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
package main
import (
"context"
"fmt"
"net/http"
"os"
"os/signal"
"strings"
"syscall"
"time"
"github.com/mccutchen/go-httpbin/v2/httpbin"
"github.com/rs/zerolog"
"github.com/rs/zerolog/hlog"
)
const (
maxBodySize = 512 * 1024 // 512kb
maxDuration = 10 * time.Second
)
var allowedRedirectDomains = []string{
"example.com",
"example.net",
"example.org",
"httpbingo.org",
}
// Exclude headers set by the fly.io platform on which we're deployed
var excludedHeaders = []string{
"fly-*",
}
func main() {
logger := zerolog.New(os.Stderr)
hostname, err := os.Hostname()
if err != nil {
logger.Warn().Msgf("error looking up hostname: %s", err)
hostname = "unknown"
}
h := httpbin.New(
httpbin.WithMaxBodySize(maxBodySize),
httpbin.WithMaxDuration(maxDuration),
httpbin.WithHostname(hostname),
httpbin.WithAllowedRedirectDomains(allowedRedirectDomains),
httpbin.WithExcludeHeaders(strings.Join(excludedHeaders, ",")),
)
var handler http.Handler
handler = h.Handler()
handler = spamFilter(handler)
handler = hlog.AccessHandler(requestLogger)(handler)
handler = hlog.NewHandler(logger)(handler)
srv := &http.Server{
Addr: fmt.Sprintf("0.0.0.0:%s", os.Getenv("PORT")),
Handler: handler,
ReadTimeout: 2 * time.Second,
ReadHeaderTimeout: 1 * time.Second,
MaxHeaderBytes: 1024 * 4, // 4kb
}
logger.Info().Msgf("listening on %s", srv.Addr)
if err := listenAndServeGracefully(srv, maxDuration); err != nil {
logger.Fatal().Msgf("error starting server: %s", err)
}
}
// spamFilter is where we attempt to discourage abusive behavior. The actual
// filtering is likely to evolve over time, based on observed behavior and
// traffic patterns.
func spamFilter(next http.Handler) http.Handler {
isSpam := func(r *http.Request) bool {
ua := r.Header.Get("User-Agent")
switch {
case r.Method == http.MethodGet && r.URL.Path == "/stream-bytes/500000" && r.URL.Query().Get("nnn") != "":
// https://github.com/mccutchen/httpbingo.org/issues/1
return true
case ua == "Envoy/HC":
// https://github.com/mccutchen/httpbingo.org/issues/3
return true
case ua == "Apache-HttpClient/4.5.14 (Java/21.0.2)" && r.Method == http.MethodGet && r.URL.Path == "/anything":
// https://github.com/mccutchen/httpbingo.org/issues/4
return true
case ua == "":
// https://github.com/mccutchen/httpbingo.org/issues/5
//
// this is more aggressive than strictly necessary for that particular
// traffic pattern, but it seems reasonable to me to reject all traffic
// that doesn't include at least *some* User-Agent identifier
return true
default:
return false
}
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if isSpam(r) {
w.WriteHeader(http.StatusPaymentRequired)
return
}
next.ServeHTTP(w, r)
})
}
func requestLogger(r *http.Request, status int, size int, duration time.Duration) {
hlog.FromRequest(r).
Info().
Int("status", status).
Str("method", r.Method).
Str("uri", r.RequestURI).
Int("size_bytes", size).
Str("user_agent", r.Header.Get("User-Agent")).
Str("client_ip", r.Header.Get("Fly-Client-IP")).
Float64("duration_ms", duration.Seconds()*1e3). // https://github.com/golang/go/issues/5491#issuecomment-66079585
Send()
}
func listenAndServeGracefully(srv *http.Server, shutdownTimeout time.Duration) error {
doneCh := make(chan error, 1)
go func() {
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, syscall.SIGTERM, syscall.SIGINT)
<-sigCh
ctx, cancel := context.WithTimeout(context.Background(), shutdownTimeout)
defer cancel()
doneCh <- srv.Shutdown(ctx)
}()
if err := srv.ListenAndServe(); err != http.ErrServerClosed {
return err
}
return <-doneCh
}