forked from QuantumNous/new-api
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrusted_proxies.go
More file actions
51 lines (46 loc) · 1.4 KB
/
Copy pathtrusted_proxies.go
File metadata and controls
51 lines (46 loc) · 1.4 KB
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
package middleware
import (
"errors"
"fmt"
"log"
"os"
"strings"
"github.com/gin-gonic/gin"
)
var defaultTrustedProxyCIDRs = []string{
"127.0.0.0/8",
"::1",
"10.0.0.0/8",
"172.16.0.0/12",
"192.168.0.0/16",
"fc00::/7",
}
func ConfigureTrustedProxies(engine *gin.Engine) error {
rawTrustedProxies := strings.TrimSpace(os.Getenv("TRUSTED_PROXIES"))
if rawTrustedProxies == "" {
log.Print("WARNING: TRUSTED_PROXIES is unset or blank; trusting loopback, RFC 1918, and IPv6 ULA proxy addresses for compatibility. Set TRUSTED_PROXIES=none to trust no proxies, or configure explicit proxy IPs/CIDRs to replace these defaults.")
return engine.SetTrustedProxies(defaultTrustedProxyCIDRs)
}
if strings.EqualFold(rawTrustedProxies, "none") {
return engine.SetTrustedProxies(nil)
}
parts := strings.Split(rawTrustedProxies, ",")
trustedProxies := make([]string, 0, len(parts))
for _, part := range parts {
trustedProxy := strings.TrimSpace(part)
if trustedProxy == "" {
continue
}
if strings.EqualFold(trustedProxy, "none") {
return errors.New("TRUSTED_PROXIES=none must be used alone")
}
trustedProxies = append(trustedProxies, trustedProxy)
}
if len(trustedProxies) == 0 {
return errors.New("TRUSTED_PROXIES does not contain an IP address or CIDR")
}
if err := engine.SetTrustedProxies(trustedProxies); err != nil {
return fmt.Errorf("invalid TRUSTED_PROXIES: %w", err)
}
return nil
}