-
Notifications
You must be signed in to change notification settings - Fork 1
/
middlewareHTTP.go
74 lines (62 loc) · 2.23 KB
/
middlewareHTTP.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
package main
import (
"fmt"
"net"
"net/http"
"net/url"
)
// This is SECURITY Control Middleware
func middlewareHTTPHandler(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Get Client IP address for Rate Limitter.
ip, _, err := net.SplitHostPort(r.RemoteAddr) // _ is port but not required.
// If system cannot parse the addr. (may be socket in next)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, `{"code":"%s","err":"%s"}`, http.StatusText(http.StatusInternalServerError), err.Error())
return
}
// If every basic security checks is ok, Let's control the ratio of request from client to preventing over usage and also any proxy.
limiter := limiter.GetLimiter(ip)
if !limiter.Allow() {
http.Error(w, http.StatusText(http.StatusTooManyRequests), http.StatusTooManyRequests)
return
}
// Define request method.
httpScheme := "https"
if r.TLS == nil {
httpScheme = "http"
}
// This may be requests comes from different domain, port or http scheme.
if allowedDomain != "" {
if r.Host != allowedDomain {
w.WriteHeader(http.StatusNotAcceptable)
fmt.Fprintf(w, `{"code":"NotAcceptable","err":"Request Domain is different", "requestDomain": "%s"}`, httpScheme+"://"+r.Host)
return
}
}
// Referer Control for forbiding embedding this service to unknown websites.
middleReferer := r.Header.Get("referer")
// Parse referer url to get host.
u, err := url.Parse(middleReferer)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, `{"code":"%s","err":"%s"}`, http.StatusText(http.StatusInternalServerError), err.Error())
return
}
// check if referrers controlled
if allowedReferrers != nil {
// Check is referer in list.
if !contains(allowedReferrers, u.Host) {
w.WriteHeader(http.StatusNotAcceptable)
fmt.Fprintf(w, `{"code":"NotAcceptable","err":"Referrer is not allowed", "referrer": "%s"}`, u.Host)
return
}
}
w.Header().Set("CONTENT-SECURITY-POLICY", "default-src 'none'; style-src 'unsafe-inline';base-uri 'self';")
if u.Scheme != "" {
w.Header().Set("Access-Control-Allow-Origin", u.Scheme+"://"+u.Host)
}
next.ServeHTTP(w, r)
})
}