Debian Codegraph @

internal/test/testsuite/testsuite.go

raw
1 package testsuite
2
3 import (
4 "bufio"
5 "context"
6 "encoding/json"
7 "fmt"
8 "io"
9 "net"
10 "net/http"
11 "net/http/cookiejar"
12 "net/http/httptest"
13 "net/url"
14 "testing"
15 "time"
16
17 "github.com/jkroepke/openvpn-auth-oauth2/v2/internal/config"
18 "github.com/jkroepke/openvpn-auth-oauth2/v2/internal/config/types"
19 "github.com/jkroepke/openvpn-auth-oauth2/v2/internal/crypto"
20 "github.com/jkroepke/openvpn-auth-oauth2/v2/internal/httphandler"
21 "github.com/jkroepke/openvpn-auth-oauth2/v2/internal/oauth2"
22 "github.com/jkroepke/openvpn-auth-oauth2/v2/internal/oauth2/providers/generic"
23 "github.com/jkroepke/openvpn-auth-oauth2/v2/internal/oauth2/providers/github"
24 "github.com/jkroepke/openvpn-auth-oauth2/v2/internal/oauth2/providers/google"
25 "github.com/jkroepke/openvpn-auth-oauth2/v2/internal/openvpn"
26 "github.com/jkroepke/openvpn-auth-oauth2/v2/internal/test/testlogger"
27 "github.com/jkroepke/openvpn-auth-oauth2/v2/internal/tokenstorage"
28 "github.com/jkroepke/openvpn-auth-oauth2/v2/internal/utils"
29 "github.com/stretchr/testify/require"
30 oidcstorage "github.com/zitadel/oidc/v3/example/server/storage"
31 "github.com/zitadel/oidc/v3/pkg/op"
32 "golang.org/x/net/nettest"
33 )
34
35 type Suite struct {
36 managementInterface net.Listener
37 managementInterfaceConn net.Conn
38 rt http.RoundTripper
39 logger *testlogger.Logger
40 httpClient *http.Client
41 httpClientListener *httptest.Server
42 managementInterfaceConnReader *bufio.Reader
43 openVPNClient *openvpn.Client
44 oAuth2Client *oauth2.Client
45 errOpenVPNClientCh chan error
46 conf *config.Config
47 }
48
49 func NewCipher(tb testing.TB) *crypto.Cipher {
50 tb.Helper()
51
52 cipher, err := crypto.New(Secret)
53 require.NoError(tb, err)
54
55 return cipher
56 }
57
58 func New(conf *config.Config, opts ...Options) *Suite {
59 suite := &Suite{
60 conf: conf,
61 logger: testlogger.New(),
62 rt: http.DefaultTransport,
63 }
64
65 for _, opt := range opts {
66 if opt != nil {
67 opt(suite)
68 }
69 }
70
71 suite.httpClient = &http.Client{Transport: NewMockRoundTripper(utils.NewUserAgentTransport(suite.rt))}
72
73 return suite
74 }
75
76 // SetupMockEnvironment sets up an OpenVPN management interface and a mock OIDC
77 // provider. It returns the adjusted configuration and helper instances used in
78 // tests.
79 func (s *Suite) SetupMockEnvironment(ctx context.Context, tb testing.TB, opConf *op.Config) <-chan error {
80 tb.Helper()
81
82 s.setupManagementInterface(tb)
83 s.applyManagementDefaults()
84
85 // clientListener must not be closed because it is used by the httpClientListener.
86 clientListener, err := nettest.NewLocalListener("tcp")
87 require.NoError(tb, err)
88
89 s.SetupOIDCServer(tb, clientListener, opConf)
90
91 if s.conf.HTTP.AssetPath.IsEmpty() {
92 s.conf.HTTP.AssetPath = config.Defaults.HTTP.AssetPath
93 }
94
95 if s.conf.HTTP.Template.IsEmpty() {
96 s.conf.HTTP.Template = config.Defaults.HTTP.Template
97 }
98
99 if s.conf.OpenVPN.ClientConfig.Path.IsEmpty() {
100 s.conf.OpenVPN.ClientConfig.Path = config.Defaults.OpenVPN.ClientConfig.Path
101 }
102
103 tokenStorage, err := tokenstorage.NewInMemory(Secret, s.conf.OAuth2.Refresh.Expires)
104 require.NoError(tb, err)
105
106 s.oAuth2Client, s.openVPNClient = s.SetupOpenVPNOAuth2Clients(ctx, tb, tokenStorage)
107
108 httpHandler := httphandler.New(s.conf, s.oAuth2Client)
109 s.httpClientListener = httptest.NewUnstartedServer(httpHandler)
110 require.NoError(tb, s.httpClientListener.Listener.Close())
111
112 s.httpClientListener.Listener = clientListener
113 s.httpClientListener.Start()
114 tb.Cleanup(s.httpClientListener.Close)
115
116 httpClientListenerClient := s.httpClientListener.Client()
117 httpClientListenerClient.Transport = s.httpClient.Transport
118
119 jar, err := cookiejar.New(nil)
120 require.NoError(tb, err)
121
122 httpClientListenerClient.Jar = jar
123
124 s.httpClient = httpClientListenerClient
125
126 errOpenVPNClientCh := s.connectOpenVPNManagement(ctx, tb)
127
128 listen, err := WaitUntilListening(ctx, tb, s.httpClientListener.Listener.Addr().Network(), s.httpClientListener.Listener.Addr().String())
129 require.NoError(tb, err)
130 require.NoError(tb, listen.Close())
131
132 return errOpenVPNClientCh
133 }
134
135 // SetupOIDCServer starts a minimal OIDC server used for integration tests.
136 func (s *Suite) SetupOIDCServer(tb testing.TB, clientListener net.Listener, opConfig *op.Config) (*httptest.Server, types.URL, config.OAuth2Client) {
137 tb.Helper()
138
139 clientSecret := Secret
140
141 client := oidcstorage.WebClient(
142 "clientID",
143 clientSecret,
144 fmt.Sprintf("http://%s/oauth2/callback", clientListener.Addr().String()),
145 fmt.Sprintf("https://%s/oauth2/callback", clientListener.Addr().String()),
146 )
147
148 clients := map[string]*oidcstorage.Client{
149 client.GetID(): client,
150 }
151
152 opStorage := oidcstorage.NewStorageWithClients(oidcstorage.NewUserStore("http://localhost"), clients)
153
154 if opConfig == nil {
155 opConfig = &op.Config{
156 CryptoKey: HashSecret,
157 DefaultLogoutRedirectURI: "/",
158 CodeMethodS256: true,
159 AuthMethodPost: true,
160 AuthMethodPrivateKeyJWT: true,
161 GrantTypeRefreshToken: true,
162 RequestObjectSupported: true,
163 SupportedUILocales: SupportedUILocales,
164 }
165 }
166
167 opProvider, err := op.NewProvider(opConfig, opStorage, op.IssuerFromHost(""), op.WithAllowInsecure())
168 require.NoError(tb, err, s.Logs())
169
170 httpHandler := http.NewServeMux()
171 httpHandler.Handle("/", opProvider)
172 httpHandler.Handle("/login/username", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
173 // G120: Parsing form data without limiting request body size can allow memory exhaustion
174 r.Body = http.MaxBytesReader(w, r.Body, 1<<20)
175
176 _ = opStorage.CheckUsernamePassword("test-user@localhost", "verysecure", r.FormValue("authRequestID"))
177 http.Redirect(w, r, op.AuthCallbackURL(opProvider)(r.Context(), r.FormValue("authRequestID")), http.StatusFound)
178 }))
179 httpHandler.Handle(opProvider.UserinfoEndpoint().Relative(), http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
180 wMock := httptest.NewRecorder()
181
182 opProvider.ServeHTTP(wMock, r)
183
184 if wMock.Code != http.StatusOK {
185 http.Error(w, wMock.Body.String(), wMock.Code)
186
187 return
188 }
189
190 userInfo := wMock.Body.String()
191
192 var userInfoMap map[string]any
193 if err := json.Unmarshal([]byte(userInfo), &userInfoMap); err != nil {
194 http.Error(w, "Invalid user info JSON", http.StatusInternalServerError)
195
196 return
197 }
198
199 userInfoMap["groups"] = []string{"group1", "group2"}
200
201 updatedUserInfo, err := json.Marshal(userInfoMap)
202 if err != nil {
203 http.Error(w, "Failed to marshal user info JSON", http.StatusInternalServerError)
204
205 return
206 }
207
208 w.WriteHeader(wMock.Code)
209 _, _ = w.Write(updatedUserInfo)
210 }))
211
212 resourceServer := s.CreateHTTPTestServer(tb, httpHandler)
213
214 resourceServerURL, err := types.NewURL(resourceServer.URL)
215 require.NoError(tb, err, s.Logs())
216
217 clientCredentials := config.OAuth2Client{ID: client.GetID(), Secret: types.Secret(clientSecret)}
218 s.applyOIDCServerConfig(clientListener, resourceServerURL, clientCredentials)
219
220 return resourceServer, resourceServerURL, clientCredentials
221 }
222
223 // SetupOpenVPNOAuth2Clients creates mocked OpenVPN and OAuth2 clients using the
224 // provided configuration.
225 func (s *Suite) SetupOpenVPNOAuth2Clients(ctx context.Context, tb testing.TB, tokenStorage tokenstorage.Storage) (*oauth2.Client, *openvpn.Client) {
226 tb.Helper()
227
228 var (
229 err error
230 provider oauth2.Provider
231 )
232
233 if s.conf.OAuth2.Provider == "" {
234 s.conf.OAuth2.Provider = generic.Name
235 }
236
237 if s.conf.OAuth2.Issuer.IsEmpty() {
238 s.conf.OAuth2.Issuer = types.URL{URL: &url.URL{Scheme: config.SchemeHTTP, Host: TestDomain}}
239 s.conf.OAuth2.Endpoints.Auth = types.URL{URL: &url.URL{Scheme: config.SchemeHTTP, Host: TestDomain, Path: "/auth"}}
240 s.conf.OAuth2.Endpoints.Token = types.URL{URL: &url.URL{Scheme: config.SchemeHTTP, Host: TestDomain, Path: "/token"}}
241 }
242
243 if s.conf.OpenVPN.CommandTimeout == 0 {
244 s.conf.OpenVPN.CommandTimeout = time.Millisecond * 300
245 }
246
247 if tokenStorage == nil {
248 refreshExpires := s.conf.OAuth2.Refresh.Expires
249 if refreshExpires == 0 {
250 refreshExpires = time.Hour
251 }
252
253 tokenStorage, err = tokenstorage.NewInMemory(Secret, refreshExpires)
254 require.NoError(tb, err)
255 }
256
257 switch s.conf.OAuth2.Provider {
258 case generic.Name:
259 provider, err = generic.NewProvider(ctx, s.conf, s.httpClient)
260 case github.Name:
261 provider, err = github.NewProvider(ctx, s.conf, s.httpClient)
262 case google.Name:
263 provider, err = google.NewProvider(ctx, s.conf, s.httpClient)
264 default:
265 tb.Fatal("unknown oauth2 provider: " + s.conf.OAuth2.Provider)
266 }
267
268 require.NoError(tb, err)
269
270 openVPNClient := openvpn.New(s.logger.Logger(), s.conf)
271 oAuth2Client, err := oauth2.New(
272 ctx,
273 s.logger.Logger(),
274 s.conf,
275 s.httpClient,
276 tokenStorage,
277 NewCipher(tb),
278 provider,
279 openVPNClient,
280 )
281 require.NoError(tb, err)
282
283 openVPNClient.SetOAuth2Client(oAuth2Client)
284
285 tb.Cleanup(func() {
286 openVPNClient.Shutdown(ctx)
287 })
288
289 return oAuth2Client, openVPNClient
290 }
291
292 func (s *Suite) SetupManagementEnvironment(ctx context.Context, tb testing.TB, tokenStorage tokenstorage.Storage) <-chan error {
293 tb.Helper()
294
295 s.setupManagementInterface(tb)
296 s.applyManagementDefaults()
297
298 if s.conf.HTTP.BaseURL.IsEmpty() {
299 s.conf.HTTP.BaseURL = types.URL{URL: &url.URL{Scheme: config.SchemeHTTP, Host: "localhost"}}
300 }
301
302 s.oAuth2Client, s.openVPNClient = s.SetupOpenVPNOAuth2Clients(ctx, tb, tokenStorage)
303
304 return s.connectOpenVPNManagement(ctx, tb)
305 }
306
307 // ConnectToManagementInterface establishes a connection to the given management
308 // interface and returns the accepted net.Conn and an error channel for the
309 // OpenVPN client.
310 func (s *Suite) ConnectToManagementInterface(ctx context.Context, tb testing.TB) {
311 tb.Helper()
312
313 s.errOpenVPNClientCh = make(chan error, 1)
314 errTCPAcceptCh := make(chan error, 1)
315
316 var err error
317
318 go func(errCh chan<- error) {
319 s.managementInterfaceConn, err = s.managementInterface.Accept()
320
321 errCh <- err
322 }(errTCPAcceptCh)
323
324 go func(errCh chan<- error) {
325 errCh <- s.openVPNClient.Connect(ctx)
326 }(s.errOpenVPNClientCh)
327
328 if err := <-errTCPAcceptCh; err != nil {
329 require.NoError(tb, err, "error accepting connection to management interface: %s", s.Logs())
330 }
331
332 select {
333 case err := <-s.errOpenVPNClientCh:
334 require.NoError(tb, err, "error connecting OpenVPN client: %s", s.Logs())
335 default:
336 }
337
338 require.NotNil(tb, s.managementInterfaceConn, "expected a connection to the management interface, but got nil. Logs: %s", s.Logs())
339
340 s.managementInterfaceConnReader = bufio.NewReader(s.managementInterfaceConn)
341 }
342
343 // SendAndExpectMessage sends a message and immediately validates the response.
344 func (s *Suite) SendAndExpectMessage(tb testing.TB, sendMessage, expectMessage string) {
345 tb.Helper()
346
347 s.SendMessagef(tb, sendMessage)
348 s.ExpectMessage(tb, expectMessage)
349 }
350
351 // SendMessagef sends a formatted string to the management interface connection.
352 func (s *Suite) SendMessagef(tb testing.TB, sendMessage string, args ...any) {
353 tb.Helper()
354
355 sendMessagef(tb, s.managementInterfaceConn, s.Logs, sendMessage, args...)
356 }
357
358 // ExpectMessage reads from the connection and compares the output with the
359 // expected message.
360 func (s *Suite) ExpectMessage(tb testing.TB, expectMessage string) {
361 tb.Helper()
362
363 expectConnMessage(tb, s.managementInterfaceConn, s.managementInterfaceConnReader, s.Logs, expectMessage)
364 }
365
366 // ExpectVersionAndReleaseHold performs the initial handshake with the mocked
367 // management interface. It checks for a version query and hold release.
368 func (s *Suite) ExpectVersionAndReleaseHold(tb testing.TB) {
369 tb.Helper()
370
371 expectVersionAndReleaseHold(tb, s.managementInterfaceConn, s.managementInterfaceConnReader, s.Logs)
372 }
373
374 // ReadLine reads a single line from the connection with a timeout.
375 func (s *Suite) ReadLine(tb testing.TB) string {
376 tb.Helper()
377
378 return readLine(tb, s.managementInterfaceConn, s.managementInterfaceConnReader)
379 }
380
381 func (s *Suite) Close(tb testing.TB) {
382 tb.Helper()
383
384 s.openVPNClient.Shutdown(tb.Context())
385
386 select {
387 case err := <-s.errOpenVPNClientCh:
388 require.NoError(tb, err, "error shutting down OpenVPN client: %s", s.Logs())
389 case <-time.After(3 * time.Second):
390 tb.Fatalf("timeout waiting for connection to close. Logs:\n\n%s", s.Logs())
391 }
392 }
393
394 func (s *Suite) GetHTTPClient() *http.Client {
395 return s.httpClient
396 }
397
398 func (s *Suite) GetConfig() *config.Config {
399 return s.conf
400 }
401
402 func (s *Suite) GetOpenVPNClient() *openvpn.Client {
403 return s.openVPNClient
404 }
405
406 func (s *Suite) GetManagementInterfaceConn() net.Conn {
407 return s.managementInterfaceConn
408 }
409
410 func (s *Suite) GetManagementInterfaceConnReader() *bufio.Reader {
411 return s.managementInterfaceConnReader
412 }
413
414 func (s *Suite) GetHTTPServerURL() string {
415 return s.httpClientListener.URL
416 }
417
418 func (s *Suite) DoHTTPRequest(tb testing.TB, method, requestURL string, header http.Header, body io.Reader) (*http.Response, []byte, error) {
419 tb.Helper()
420
421 return DoHTTPRequest(tb, s.httpClient, s.httpClientListener.URL, method, requestURL, header, body)
422 }
423
424 func (s *Suite) setupManagementInterface(tb testing.TB) {
425 tb.Helper()
426
427 s.managementInterface = s.CreateTCPListener(tb)
428
429 tb.Cleanup(func() {
430 require.NoError(tb, s.managementInterface.Close())
431 })
432
433 s.conf.OpenVPN.Addr = types.URL{URL: &url.URL{Scheme: s.managementInterface.Addr().Network(), Host: s.managementInterface.Addr().String()}}
434 }
435
436 func (s *Suite) applyManagementDefaults() {
437 if s.conf.HTTP.Secret == "" {
438 s.conf.HTTP.Secret = Secret
439 }
440
441 if s.conf.OpenVPN.Bypass.CommonNames == nil {
442 s.conf.OpenVPN.Bypass.CommonNames = make(types.RegexpSlice, 0)
443 }
444 }
445
446 func (s *Suite) applyOIDCServerConfig(clientListener net.Listener, resourceServerURL types.URL, clientCredentials config.OAuth2Client) {
447 s.conf.HTTP.BaseURL = types.URL{URL: &url.URL{Scheme: config.SchemeHTTP, Host: clientListener.Addr().String()}}
448
449 if s.conf.HTTP.Secret == "" {
450 s.conf.HTTP.Secret = Secret
451 }
452
453 s.conf.OAuth2.Issuer = resourceServerURL
454 s.conf.OAuth2.Nonce = true // enable nonce for mock testing
455 s.conf.OAuth2.RefreshNonce = config.OAuth2RefreshNonceEmpty // use empty nonce for refresh to avoid mock issues
456
457 if s.conf.OAuth2.Client.ID == "" {
458 s.conf.OAuth2.Client.ID = clientCredentials.ID
459 }
460
461 if s.conf.OAuth2.Client.Secret.String() == "" {
462 s.conf.OAuth2.Client.Secret = clientCredentials.Secret
463 }
464
465 if s.conf.OAuth2.Refresh.Expires.String() == "" {
466 s.conf.OAuth2.Refresh.Expires = time.Hour
467 }
468 }
469
470 func (s *Suite) connectOpenVPNManagement(ctx context.Context, tb testing.TB) <-chan error {
471 tb.Helper()
472
473 s.ConnectToManagementInterface(ctx, tb)
474
475 return s.errOpenVPNClientCh
476 }