-
Notifications
You must be signed in to change notification settings - Fork 8
/
authenticator.go
88 lines (78 loc) · 2.24 KB
/
authenticator.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
package main
import (
"fmt"
"net"
"net/http"
"strings"
"sync"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/tonkeeper/bridge/config"
"golang.org/x/exp/slices"
)
var tokenUsageMetric = promauto.NewCounterVec(prometheus.CounterOpts{
Name: "bridge_token_usage",
}, []string{"token"})
// ConnectionsLimiter is a middleware that limits the number of simultaneous connections per IP.
type ConnectionsLimiter struct {
mu sync.Mutex
connections map[string]int
max int
}
func newConnectionLimiter(i int) *ConnectionsLimiter {
return &ConnectionsLimiter{
connections: map[string]int{},
max: i,
}
}
// leaseConnection increases a number of connections per given token and
// returns a release function to be called once a request is finished.
// If the token reaches the limit of max simultaneous connections, leaseConnection returns an error.
func (auth *ConnectionsLimiter) leaseConnection(request *http.Request) (release func(), err error) {
key := fmt.Sprintf("ip-%v", realIP(request))
auth.mu.Lock()
defer auth.mu.Unlock()
if auth.connections[key] >= auth.max {
return nil, fmt.Errorf("you have reached the limit of streaming connections: %v max", auth.max)
}
auth.connections[key] += 1
return func() {
auth.mu.Lock()
defer auth.mu.Unlock()
auth.connections[key] -= 1
if auth.connections[key] == 0 {
delete(auth.connections, key)
}
}, nil
}
func realIP(request *http.Request) string {
// Fall back to legacy behavior
if ip := request.Header.Get("X-Forwarded-For"); ip != "" {
i := strings.IndexAny(ip, ",")
if i > 0 {
return strings.Trim(ip[:i], "[] \t")
}
return ip
}
if ip := request.Header.Get("X-Real-Ip"); ip != "" {
return strings.Trim(ip, "[]")
}
ra, _, _ := net.SplitHostPort(request.RemoteAddr)
return ra
}
func skipRateLimitsByToken(request *http.Request) bool {
if request == nil {
return false
}
authorization := request.Header.Get("Authorization")
if authorization == "" {
return false
}
token := strings.TrimPrefix(authorization, "Bearer ")
exist := slices.Contains(config.Config.RateLimitsByPassToken, token)
if exist {
tokenUsageMetric.WithLabelValues(token).Inc()
return true
}
return false
}