-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathforward_auth_grpc_test.go
318 lines (243 loc) · 7.62 KB
/
forward_auth_grpc_test.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
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
package main
import (
"crypto/tls"
"crypto/x509"
"net"
"os"
"testing"
pb "github.com/morzan1001/forward_auth_grpc_plugin/proto"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
)
// setupTestWithConfig sets up a gRPC server with the given configuration and mock service.
func setupTestWithConfig(t *testing.T, mock pb.AuthServiceServer, config *Config) (*GRPCForwardAuth, func()) {
lis, err := net.Listen("tcp", config.Address)
require.NoError(t, err)
var s *grpc.Server
if config.UseTLS {
var creds credentials.TransportCredentials
if config.CACertPath != "" {
// If only one CA certificate is provided, we use a self-signed certificate
cert, err := tls.LoadX509KeyPair("certs/dummy-server.crt", "certs/dummy-server.key")
require.NoError(t, err)
caCert, err := os.ReadFile(config.CACertPath)
require.NoError(t, err)
caCertPool := x509.NewCertPool()
ok := caCertPool.AppendCertsFromPEM(caCert)
require.True(t, ok, "Failed to parse CA certificate")
tlsConfig := &tls.Config{
Certificates: []tls.Certificate{cert},
ClientCAs: caCertPool,
}
creds = credentials.NewTLS(tlsConfig)
} else {
t.Fatal("TLS activated, but neither server certificate nor CA certificate specified")
}
s = grpc.NewServer(grpc.Creds(creds))
} else {
s = grpc.NewServer()
}
pb.RegisterAuthServiceServer(s, mock)
go func() {
if err := s.Serve(lis); err != nil {
t.Logf("Server error: %v", err)
}
}()
auth, err := New(config)
require.NoError(t, err)
cleanup := func() {
s.Stop()
lis.Close()
}
return auth, cleanup
}
// TestGRPCForwardAuth_FailedAuthentication tests failed authentication.
func TestGRPCForwardAuth_FailedAuthentication(t *testing.T) {
mock := &MockAuthService{
allowAuth: false,
message: "invalid token",
}
config := &Config{
Address: "localhost:50052",
TokenHeader: "Authorization",
UseTLS: false,
}
auth, cleanup := setupTestWithConfig(t, mock, config)
defer cleanup()
req := NewMockRequest()
resp := NewMockResponse()
req.Headers().Set("Authorization", "Bearer invalid-token")
next, _ := auth.handleRequest(req, resp)
assert.False(t, next)
assert.Equal(t, uint32(401), resp.GetStatusCode())
}
// TestGRPCForwardAuth_MissingToken tests the behavior when the token is missing.
func TestGRPCForwardAuth_MissingToken(t *testing.T) {
mock := &MockAuthService{
allowAuth: true,
}
config := &Config{
Address: "localhost:50053",
TokenHeader: "Authorization",
UseTLS: false,
}
auth, cleanup := setupTestWithConfig(t, mock, config)
defer cleanup()
req := NewMockRequest()
resp := NewMockResponse()
next, _ := auth.handleRequest(req, resp)
assert.False(t, next)
assert.Equal(t, uint32(401), resp.GetStatusCode())
}
// TestGRPCForwardAuth_EmptyToken tests the behavior when the token is empty.
func TestGRPCForwardAuth_EmptyToken(t *testing.T) {
mock := &MockAuthService{
allowAuth: true,
}
config := &Config{
Address: "localhost:50054",
TokenHeader: "Authorization",
UseTLS: false,
}
auth, cleanup := setupTestWithConfig(t, mock, config)
defer cleanup()
req := NewMockRequest()
resp := NewMockResponse()
req.Headers().Set("Authorization", "")
next, _ := auth.handleRequest(req, resp)
assert.False(t, next)
assert.Equal(t, uint32(401), resp.GetStatusCode())
}
// TestGRPCForwardAuth_WithTLSAndCACert tests the behavior with TLS and CA certificate.
func TestGRPCForwardAuth_WithTLSAndCACert(t *testing.T) {
mock := &MockAuthService{
allowAuth: true,
}
config := &Config{
Address: "localhost:50055",
TokenHeader: "Authorization",
UseTLS: true,
CACertPath: "certs/dummy-ca.crt",
}
auth, cleanup := setupTestWithConfig(t, mock, config)
defer cleanup()
req := NewMockRequest()
resp := NewMockResponse()
req.Headers().Set("Authorization", "Bearer valid-token")
next, _ := auth.handleRequest(req, resp)
assert.True(t, next)
assert.Equal(t, uint32(200), resp.GetStatusCode())
}
// TestGRPCForwardAuth_WithoutTLS tests the behavior without TLS.
func TestGRPCForwardAuth_WithoutTLS(t *testing.T) {
mock := &MockAuthService{
allowAuth: true,
}
config := &Config{
Address: "localhost:50056",
TokenHeader: "Authorization",
UseTLS: false,
}
auth, cleanup := setupTestWithConfig(t, mock, config)
defer cleanup()
req := NewMockRequest()
resp := NewMockResponse()
req.Headers().Set("Authorization", "Bearer valid-token")
next, _ := auth.handleRequest(req, resp)
assert.True(t, next)
assert.Equal(t, uint32(200), resp.GetStatusCode())
}
// TestGRPCForwardAuth_EmptyAddress tests the behavior with an empty address.
func TestGRPCForwardAuth_EmptyAddress(t *testing.T) {
config := &Config{
Address: "",
TokenHeader: "Authorization",
UseTLS: false,
}
_, err := New(config)
assert.Error(t, err)
}
// TestGRPCForwardAuth_InvalidCACertPath tests the behavior with an invalid CA certificate path.
func TestGRPCForwardAuth_InvalidCACertPath(t *testing.T) {
config := &Config{
Address: "localhost:50057",
TokenHeader: "Authorization",
UseTLS: true,
CACertPath: "nonexistent.crt",
}
_, err := New(config)
assert.Error(t, err)
}
// TestGRPCForwardAuth_CustomTokenHeader tests the behavior with a custom token header.
func TestGRPCForwardAuth_CustomTokenHeader(t *testing.T) {
mock := &MockAuthService{
allowAuth: true,
}
config := &Config{
Address: "localhost:50058",
TokenHeader: "X-Custom-Token",
UseTLS: false,
}
auth, cleanup := setupTestWithConfig(t, mock, config)
defer cleanup()
req := NewMockRequest()
resp := NewMockResponse()
req.Headers().Set("X-Custom-Token", "Bearer valid-token")
next, _ := auth.handleRequest(req, resp)
assert.True(t, next)
assert.Equal(t, uint32(200), resp.GetStatusCode())
}
// TestGRPCForwardAuth_MetadataHandling tests the handling of complex metadata.
func TestGRPCForwardAuth_MetadataHandling(t *testing.T) {
complexMetadata := map[string]string{
"user-id": "123",
"role": "admin",
"permissions": "read,write",
"tenant": "org1",
}
mock := &MockAuthService{
allowAuth: true,
metadata: complexMetadata,
}
config := &Config{
Address: "localhost:50059",
TokenHeader: "Authorization",
UseTLS: false,
}
auth, cleanup := setupTestWithConfig(t, mock, config)
defer cleanup()
req := NewMockRequest()
resp := NewMockResponse()
req.Headers().Set("Authorization", "Bearer valid-token")
next, _ := auth.handleRequest(req, resp)
assert.True(t, next)
for key, value := range complexMetadata {
headerValue, ok := req.Headers().Get(key)
assert.True(t, ok)
assert.Equal(t, value, headerValue)
}
}
// TestGRPCForwardAuth_ServiceUnavailable tests the behavior when the auth service is unavailable.
func TestGRPCForwardAuth_ServiceUnavailable(t *testing.T) {
config := &Config{
Address: "invalid:50060",
TokenHeader: "Authorization",
UseTLS: false,
}
// Directly initialize the service without setting up a gRPC server
auth, err := New(config)
require.NoError(t, err)
req := NewMockRequest()
resp := NewMockResponse()
req.Headers().Set("Authorization", "Bearer valid-token")
next, _ := auth.handleRequest(req, resp)
assert.False(t, next, "Request should not be forwarded when auth service is unavailable")
assert.Equal(t, uint32(401), resp.GetStatusCode(),
"Should return 401 Unauthorized when auth service is not reachable")
// Test which error message is returned.
// In order not to leak any internal information, a standard code with a standard message is expected.
body := resp.Body().(*MockBody)
assert.Contains(t, string(body.data), "authentication failed")
}