Debian Codegraph @

internal/oauth2/utils_test.go

raw
1 package oauth2 //nolint:testpackage
2
3 import (
4 "net/http"
5 "testing"
6
7 "github.com/jkroepke/openvpn-auth-oauth2/v2/internal/config"
8 "github.com/jkroepke/openvpn-auth-oauth2/v2/internal/config/types"
9 "github.com/jkroepke/openvpn-auth-oauth2/v2/internal/state"
10 "github.com/stretchr/testify/require"
11 )
12
13 func TestCheckClientIPAddrIPv6RemoteAddr(t *testing.T) {
14 t.Parallel()
15
16 conf := config.Defaults
17 conf.HTTP.Check.IPAddr = true
18
19 req := &http.Request{
20 RemoteAddr: "[2001:db8::1]:12345",
21 Header: make(http.Header),
22 }
23 session := state.State{IPAddr: "2001:db8::1"}
24
25 require.NoError(t, checkClientIPAddr(req, &conf, session))
26 }
27
28 func TestCheckClientIPAddrProxyHeaders(t *testing.T) {
29 t.Parallel()
30
31 for _, tc := range []struct {
32 name string
33 remoteAddr string
34 trustedProxies []string
35 sessionIP string
36 expectedErr string
37 }{
38 {
39 name: "trusted proxy",
40 remoteAddr: "10.0.0.1:12345",
41 trustedProxies: []string{"10.0.0.0/24"},
42 sessionIP: "127.0.0.1",
43 },
44 {
45 name: "untrusted proxy",
46 remoteAddr: "10.0.0.1:12345",
47 trustedProxies: []string{"192.0.2.0/24"},
48 sessionIP: "127.0.0.1",
49 expectedErr: "client rejected: http client ip 10.0.0.1 and vpn ip 127.0.0.1 is different",
50 },
51 {
52 name: "trusted proxy with spoofed leading value",
53 remoteAddr: "10.0.0.1:12345",
54 trustedProxies: []string{"10.0.0.0/24"},
55 sessionIP: "127.0.0.1",
56 expectedErr: "client rejected: http client ip 203.0.113.10 and vpn ip 127.0.0.1 is different",
57 },
58 {
59 name: "trusted proxy with multiple header values",
60 remoteAddr: "10.0.0.1:12345",
61 trustedProxies: []string{"10.0.0.0/24"},
62 sessionIP: "203.0.113.10",
63 },
64 {
65 name: "trusted ipv6 proxy",
66 remoteAddr: "[2001:db8::2]:12345",
67 trustedProxies: []string{"2001:db8::/64"},
68 sessionIP: "2001:db8::1",
69 },
70 } {
71 t.Run(tc.name, func(t *testing.T) {
72 t.Parallel()
73
74 conf := config.Defaults
75 conf.HTTP.Check.IPAddr = true
76 conf.HTTP.EnableProxyHeaders = true
77 conf.HTTP.TrustedProxies = types.StringSlice(tc.trustedProxies)
78
79 req := &http.Request{
80 RemoteAddr: tc.remoteAddr,
81 Header: http.Header{"X-Forwarded-For": []string{"127.0.0.1, 10.0.0.1"}},
82 }
83 switch tc.name {
84 case "trusted ipv6 proxy":
85 req.Header.Set("X-Forwarded-For", "2001:db8::1, 2001:db8::2")
86 case "trusted proxy with spoofed leading value":
87 req.Header.Set("X-Forwarded-For", "127.0.0.1, 203.0.113.10")
88 case "trusted proxy with multiple header values":
89 req.Header = http.Header{
90 "X-Forwarded-For": []string{"127.0.0.1", "203.0.113.10"},
91 }
92 }
93
94 err := checkClientIPAddr(req, &conf, state.State{IPAddr: tc.sessionIP})
95 if tc.expectedErr == "" {
96 require.NoError(t, err)
97
98 return
99 }
100
101 require.EqualError(t, err, tc.expectedErr)
102 })
103 }
104 }