File: realip_test.go

package info (click to toggle)
golang-github-grpc-ecosystem-go-grpc-middleware 2.1.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,464 kB
  • sloc: makefile: 107; sh: 9
file content (513 lines) | stat: -rw-r--r-- 14,682 bytes parent folder | download
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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
// Copyright (c) The go-grpc-middleware Authors.
// Licensed under the Apache License 2.0.

package realip

import (
	"context"
	"fmt"
	"net"
	"net/netip"
	"testing"

	"github.com/stretchr/testify/assert"
	"google.golang.org/grpc"
	"google.golang.org/grpc/metadata"
	"google.golang.org/grpc/peer"
)

var (
	localnet []netip.Prefix = []netip.Prefix{
		netip.MustParsePrefix("127.0.0.1/8"),
		netip.MustParsePrefix("::1/128"),
	}

	privatenet []netip.Prefix = []netip.Prefix{
		netip.MustParsePrefix("10.0.0.0/8"),
		netip.MustParsePrefix("172.16.0.0/12"),
		netip.MustParsePrefix("192.168.0.0/16"),
		netip.MustParsePrefix("2002:c0a8::/32"),
	}

	privateIP  netip.Addr = netip.MustParseAddr("192.168.0.1")
	privateIP6 netip.Addr = netip.MustParseAddr("::ffff:c0a8:1")
	publicIP   netip.Addr = netip.MustParseAddr("8.8.8.8")
	publicIP6  netip.Addr = netip.MustParseAddr("::ffff:808:808")
	localhost  netip.Addr = netip.MustParseAddr("127.0.0.1")
	localhost6 netip.Addr = netip.MustParseAddr("::1")
)

func localhostPeer() *peer.Peer {
	return &peer.Peer{
		Addr: &net.TCPAddr{
			IP: net.ParseIP(localhost.String()),
		},
	}
}

func localhost6Peer() *peer.Peer {
	return &peer.Peer{
		Addr: &net.TCPAddr{
			IP: net.ParseIP(localhost6.String()),
		},
	}
}

func publicPeer() *peer.Peer {
	return &peer.Peer{
		Addr: &net.TCPAddr{
			IP: net.ParseIP(publicIP.String()),
		},
	}
}

func privatePeer() *peer.Peer {
	return &peer.Peer{
		Addr: &net.TCPAddr{
			IP: net.ParseIP(privateIP.String()),
		},
	}
}

func private6Peer() *peer.Peer {
	return &peer.Peer{
		Addr: &net.TCPAddr{
			IP: net.ParseIP(privateIP6.String()),
		},
	}
}

type testCase struct {
	trustedPeers   []netip.Prefix
	trustedProxies []netip.Prefix
	proxiesCount   uint
	headerKeys     []string
	inputHeaders   map[string]string
	peer           *peer.Peer
	expectedIP     netip.Addr
}

func (c testCase) optsFromTesCase() []Option {
	return []Option{
		WithTrustedPeers(c.trustedPeers),
		WithTrustedProxies(c.trustedProxies),
		WithTrustedProxiesCount(c.proxiesCount),
		WithHeaders(c.headerKeys),
	}
}

func testUnaryServerInterceptor(t *testing.T, c testCase) {
	interceptor := UnaryServerInterceptorOpts(c.optsFromTesCase()...)
	handler := func(ctx context.Context, req any) (any, error) {
		ip, _ := FromContext(ctx)

		assert.Equal(t, c.expectedIP, ip)
		return nil, nil
	}
	info := &grpc.UnaryServerInfo{
		FullMethod: "FakeMethod",
	}
	ctx := context.Background()
	if c.peer != nil {
		ctx = peer.NewContext(ctx, c.peer)
	}
	if c.inputHeaders != nil {
		md := metadata.New(c.inputHeaders)
		ctx = metadata.NewIncomingContext(ctx, md)
	}

	resp, err := interceptor(ctx, nil, info, handler)
	assert.Nil(t, resp)
	assert.NoError(t, err)
}

func testStreamServerInterceptor(t *testing.T, c testCase) {
	interceptor := StreamServerInterceptorOpts(c.optsFromTesCase()...)
	handler := func(srv any, stream grpc.ServerStream) error {
		ip, _ := FromContext(stream.Context())

		assert.Equal(t, c.expectedIP, ip)
		return nil
	}
	info := &grpc.StreamServerInfo{
		FullMethod: "FakeMethod",
	}
	ctx := context.Background()
	if c.peer != nil {
		ctx = peer.NewContext(ctx, c.peer)
	}
	if c.inputHeaders != nil {
		md := metadata.New(c.inputHeaders)
		ctx = metadata.NewIncomingContext(ctx, md)
	}

	err := interceptor(nil, &serverStream{ctx: ctx}, info, handler)
	assert.NoError(t, err)
}

func TestInterceptor(t *testing.T) {
	t.Run("no peer", func(t *testing.T) {
		tc := testCase{
			// Test that if there is no peer, we don't get an IP.
			trustedPeers: localnet,
			headerKeys:   []string{XForwardedFor},
			inputHeaders: map[string]string{
				XForwardedFor: localhost.String(),
			},
			peer:       nil,
			expectedIP: netip.Addr{},
		}
		t.Run("unary", func(t *testing.T) {
			testUnaryServerInterceptor(t, tc)
		})
		t.Run("stream", func(t *testing.T) {
			testStreamServerInterceptor(t, tc)
		})
	})
	t.Run("trusted peer header csv", func(t *testing.T) {
		tc := testCase{
			// Test that if the remote peer is trusted and the header contains
			// a comma separated list of valid IPs, we get right most one.
			trustedPeers: localnet,
			headerKeys:   []string{XForwardedFor},
			inputHeaders: map[string]string{
				XForwardedFor: fmt.Sprintf("%s,%s", localhost.String(), publicIP.String()),
			},
			peer:       localhostPeer(),
			expectedIP: publicIP,
		}
		t.Run("unary", func(t *testing.T) {
			testUnaryServerInterceptor(t, tc)
		})
		t.Run("stream", func(t *testing.T) {
			testStreamServerInterceptor(t, tc)
		})
	})
	t.Run("trusted proxy list with XForwardedFor", func(t *testing.T) {
		tc := testCase{
			// Test that if the remote peer is trusted and the header contains
			// a comma separated list of valid IPs,
			// we get the first going from right to left that is not in local net
			trustedPeers:   localnet,
			trustedProxies: localnet,
			headerKeys:     []string{XForwardedFor},
			inputHeaders: map[string]string{
				XForwardedFor: fmt.Sprintf("%s,%s", publicIP.String(), localhost.String()),
			},
			peer:       localhostPeer(),
			expectedIP: publicIP,
		}
		t.Run("unary", func(t *testing.T) {
			testUnaryServerInterceptor(t, tc)
		})
		t.Run("stream", func(t *testing.T) {
			testStreamServerInterceptor(t, tc)
		})
	})
	t.Run("trusted proxy list private net with XForwardedFor", func(t *testing.T) {
		tc := testCase{
			// Test that if the remote peer is trusted and the header contains
			// a comma separated list of valid IPs,
			// we get the first going from right to left that is not in private net
			trustedPeers:   localnet,
			trustedProxies: privatenet,
			headerKeys:     []string{XForwardedFor},
			inputHeaders: map[string]string{
				XForwardedFor: fmt.Sprintf("%s,%s", publicIP.String(), localhost.String()),
			},
			peer:       localhostPeer(),
			expectedIP: localhost,
		}
		t.Run("unary", func(t *testing.T) {
			testUnaryServerInterceptor(t, tc)
		})
		t.Run("stream", func(t *testing.T) {
			testStreamServerInterceptor(t, tc)
		})
	})
	t.Run("trusted proxy count with XForwardedFor", func(t *testing.T) {
		tc := testCase{
			// Test that if the remote peer is trusted and the header contains
			// a comma separated list of valid IPs, we get right most one -1 proxiesCount.
			trustedPeers: localnet,
			proxiesCount: 1,
			headerKeys:   []string{XForwardedFor},
			inputHeaders: map[string]string{
				XForwardedFor: fmt.Sprintf("%s,%s", publicIP.String(), localhost.String()),
			},
			peer:       localhostPeer(),
			expectedIP: publicIP,
		}
		t.Run("unary", func(t *testing.T) {
			testUnaryServerInterceptor(t, tc)
		})
		t.Run("stream", func(t *testing.T) {
			testStreamServerInterceptor(t, tc)
		})
	})
	t.Run("wrong trusted proxy count with XForwardedFor", func(t *testing.T) {
		tc := testCase{
			// Test that if the remote peer is trusted and the header contains
			// a comma separated list of valid IPs,
			// we get peer ip as the proxiesCount is wrongly configured
			trustedPeers: localnet,
			proxiesCount: 10,
			headerKeys:   []string{XForwardedFor},
			inputHeaders: map[string]string{
				XForwardedFor: fmt.Sprintf("%s,%s", publicIP.String(), localhost.String()),
			},
			peer:       localhostPeer(),
			expectedIP: localhost,
		}
		t.Run("unary", func(t *testing.T) {
			testUnaryServerInterceptor(t, tc)
		})
		t.Run("stream", func(t *testing.T) {
			testStreamServerInterceptor(t, tc)
		})
	})
	t.Run("trusted peer single", func(t *testing.T) {
		tc := testCase{
			// Test that if the remote peer is trusted and the header contains
			// a single valid IP, we get that IP.
			trustedPeers: localnet,
			headerKeys:   []string{XRealIp},
			inputHeaders: map[string]string{
				XRealIp: privateIP.String(),
			},
			peer:       localhostPeer(),
			expectedIP: privateIP,
		}
		t.Run("unary", func(t *testing.T) {
			testUnaryServerInterceptor(t, tc)
		})
		t.Run("stream", func(t *testing.T) {
			testStreamServerInterceptor(t, tc)
		})
	})
	t.Run("trusted peer multiple", func(t *testing.T) {
		tc := testCase{
			// Test that if the trusted peers list is larger than 1 network and
			// the remote peer is in the third network, we get the right IP.
			trustedPeers: privatenet,
			headerKeys:   []string{TrueClientIp},
			inputHeaders: map[string]string{
				TrueClientIp: publicIP.String(),
			},
			peer:       privatePeer(),
			expectedIP: publicIP,
		}
		t.Run("unary", func(t *testing.T) {
			testUnaryServerInterceptor(t, tc)
		})
		t.Run("stream", func(t *testing.T) {
			testStreamServerInterceptor(t, tc)
		})
	})
	t.Run("untrusted peer single", func(t *testing.T) {
		tc := testCase{
			// Test that if the remote peer is not trusted and the header
			// contains a single valid IP, we get that the peer IP.
			trustedPeers: localnet,
			headerKeys:   []string{XRealIp},
			inputHeaders: map[string]string{
				XRealIp: privateIP.String(),
			},
			peer:       publicPeer(),
			expectedIP: publicIP,
		}
		t.Run("unary", func(t *testing.T) {
			testUnaryServerInterceptor(t, tc)
		})
		t.Run("stream", func(t *testing.T) {
			testStreamServerInterceptor(t, tc)
		})
	})
	t.Run("trusted peer multiple headers", func(t *testing.T) {
		tc := testCase{
			// Test that if the peer is trusted and several headers are
			// provided, the interceptor reads the IP from the first header in
			// the list.
			trustedPeers: localnet,
			headerKeys:   []string{XRealIp, TrueClientIp},
			inputHeaders: map[string]string{
				XRealIp:      privateIP.String(),
				TrueClientIp: publicIP.String(),
			},
			peer:       localhostPeer(),
			expectedIP: privateIP,
		}
		t.Run("unary", func(t *testing.T) {
			testUnaryServerInterceptor(t, tc)
		})
		t.Run("stream", func(t *testing.T) {
			testStreamServerInterceptor(t, tc)
		})
	})
	t.Run("trusted peer multiple header configured single provided", func(t *testing.T) {
		tc := testCase{
			// Test that if the peer is trusted and several headers are
			// configured, but only one is provided, the interceptor reads the
			// IP from the provided header.
			trustedPeers: localnet,
			headerKeys:   []string{XRealIp, TrueClientIp, XForwardedFor},
			inputHeaders: map[string]string{
				TrueClientIp: publicIP.String(),
			},
			peer:       localhostPeer(),
			expectedIP: publicIP,
		}
		t.Run("unary", func(t *testing.T) {
			testUnaryServerInterceptor(t, tc)
		})
		t.Run("stream", func(t *testing.T) {
			testStreamServerInterceptor(t, tc)
		})
	})
	t.Run("trusted peer multiple header configured none provided", func(t *testing.T) {
		tc := testCase{
			// Test that if the peer is trusted and several headers are, but no
			// header is provided, the interceptor reads the IP from the peer.
			//
			// This indicates that the proxy is not configured to forward the
			// IP. Using the peer IP is better than nothing.
			trustedPeers: localnet,
			headerKeys:   []string{XRealIp, TrueClientIp, XForwardedFor},
			peer:         localhostPeer(),
			expectedIP:   localhost,
		}
		t.Run("unary", func(t *testing.T) {
			testUnaryServerInterceptor(t, tc)
		})
		t.Run("stream", func(t *testing.T) {
			testStreamServerInterceptor(t, tc)
		})
	})
	t.Run("untrusted peer multiple headers", func(t *testing.T) {
		tc := testCase{
			// Test that if the peer is not trusted, but several headers are
			// provided, the interceptor reads the IP from peer.
			trustedPeers: nil,
			inputHeaders: map[string]string{
				XRealIp:      privateIP.String(),
				TrueClientIp: localhost.String(),
			},
			peer:       publicPeer(),
			expectedIP: publicIP,
		}
		t.Run("unary", func(t *testing.T) {
			testUnaryServerInterceptor(t, tc)
		})
		t.Run("stream", func(t *testing.T) {
			testStreamServerInterceptor(t, tc)
		})
	})
	t.Run("untrusted peer multiple header configured single provided", func(t *testing.T) {
		tc := testCase{
			// Test that if the peer is not trusted and several headers are
			// configured, but only one is provided, the interceptor reads the
			// IP from the peer.
			//
			// This is because the peer is untrusted, and as such we cannot
			// trust the headers.
			trustedPeers: nil,
			headerKeys:   []string{XRealIp, TrueClientIp, XForwardedFor},
			inputHeaders: map[string]string{
				TrueClientIp: publicIP.String(),
			},
			peer:       publicPeer(),
			expectedIP: publicIP,
		}
		t.Run("unary", func(t *testing.T) {
			testUnaryServerInterceptor(t, tc)
		})
		t.Run("stream", func(t *testing.T) {
			testStreamServerInterceptor(t, tc)
		})
	})
	t.Run("trusted peer malformed header", func(t *testing.T) {
		tc := testCase{
			// Test that if the peer is trusted, but the provided headers
			// contain malformed IP addresses, the interceptor reads the IP
			// from the peer.
			trustedPeers: localnet,
			headerKeys:   []string{XRealIp, TrueClientIp, XForwardedFor},
			inputHeaders: map[string]string{
				TrueClientIp: "malformed",
			},
			peer:       localhostPeer(),
			expectedIP: localhost,
		}
		t.Run("unary", func(t *testing.T) {
			testUnaryServerInterceptor(t, tc)
		})
		t.Run("stream", func(t *testing.T) {
			testStreamServerInterceptor(t, tc)
		})
	})
	t.Run("ipv6 from grpc peer", func(t *testing.T) {
		tc := testCase{
			trustedPeers: localnet,
			headerKeys:   []string{},
			peer:         localhost6Peer(),
			expectedIP:   localhost6,
		}
		t.Run("unary", func(t *testing.T) {
			testUnaryServerInterceptor(t, tc)
		})
		t.Run("stream", func(t *testing.T) {
			testStreamServerInterceptor(t, tc)
		})
	})
	t.Run("ipv6 from header", func(t *testing.T) {
		tc := testCase{
			trustedPeers: privatenet,
			headerKeys:   []string{XForwardedFor},
			inputHeaders: map[string]string{
				XForwardedFor: publicIP6.String(),
			},
			peer:       private6Peer(),
			expectedIP: publicIP6,
		}
		t.Run("unary", func(t *testing.T) {
			testUnaryServerInterceptor(t, tc)
		})
		t.Run("stream", func(t *testing.T) {
			testStreamServerInterceptor(t, tc)
		})
	})
	t.Run("unix", func(t *testing.T) {
		tc := testCase{
			trustedPeers: localnet,
			headerKeys:   []string{XRealIp},
			peer: &peer.Peer{
				Addr: &net.UnixAddr{Name: "unix", Net: "unix"},
			},
			expectedIP: netip.Addr{},
		}
		t.Run("unary", func(t *testing.T) {
			testUnaryServerInterceptor(t, tc)
		})
		t.Run("stream", func(t *testing.T) {
			testStreamServerInterceptor(t, tc)
		})
	})
	t.Run("header casing", func(t *testing.T) {
		tc := testCase{
			// Test that header casing is ignored.
			trustedPeers: localnet,
			headerKeys:   []string{XRealIp},
			inputHeaders: map[string]string{
				"X-Real-IP": privateIP.String(),
			},
			peer:       localhostPeer(),
			expectedIP: privateIP,
		}
		t.Run("unary", func(t *testing.T) {
			testUnaryServerInterceptor(t, tc)
		})
		t.Run("stream", func(t *testing.T) {
			testStreamServerInterceptor(t, tc)
		})
	})
}