Debian Codegraph @

internal/config/config_test.go

raw
1 package config_test
2
3 import (
4 "bytes"
5 "flag"
6 "io"
7 "log/slog"
8 "net/url"
9 "os"
10 "path/filepath"
11 "regexp"
12 "slices"
13 "testing"
14 "time"
15
16 "github.com/jkroepke/openvpn-auth-oauth2/v2/internal/config"
17 "github.com/jkroepke/openvpn-auth-oauth2/v2/internal/config/types"
18 oauth2types "github.com/jkroepke/openvpn-auth-oauth2/v2/internal/oauth2/types"
19 "github.com/jkroepke/openvpn-auth-oauth2/v2/internal/test/testsuite"
20 "github.com/stretchr/testify/assert"
21 "github.com/stretchr/testify/require"
22 "golang.org/x/oauth2"
23 )
24
25 //goland:noinspection RegExpUnnecessaryNonCapturingGroup
26 func TestConfig(t *testing.T) {
27 t.Parallel()
28
29 for _, tc := range []struct {
30 name string
31 configFile string
32 conf config.Config
33 err error
34 }{
35 {
36 "empty file",
37 "",
38 config.Defaults,
39 nil,
40 },
41 {
42 "minimal file",
43 // language=yaml
44 `
45 oauth2:
46 issuer: "https://company.zitadel.cloud"
47 client:
48 id: "test"
49 secret: "test"
50 http:
51 secret: "1jd93h5b6s82lf03jh5b2hf9"
52 `,
53 func() config.Config {
54 conf := config.Defaults
55 conf.HTTP.Secret = "1jd93h5b6s82lf03jh5b2hf9"
56 conf.OAuth2.Issuer = types.URL{URL: &url.URL{
57 Scheme: "https",
58 Host: "company.zitadel.cloud",
59 }}
60 conf.OAuth2.Client.ID = "test"
61 conf.OAuth2.Client.Secret = "test"
62
63 return conf
64 }(),
65 nil,
66 },
67 {
68 "full file",
69 // language=yaml
70 `
71 debug:
72 pprof: true
73 listen: :9002
74 log:
75 format: json
76 level: DEBUG
77 vpn-client-ip: false
78 oauth2:
79 issuer: "https://company.zitadel.cloud"
80 client:
81 id: "test"
82 secret: "test"
83 private-key-id: "openvpn-auth-oauth2"
84 validate:
85 groups:
86 - "test"
87 - "test2"
88 expression: "openvpn.commonName == token.claims.preferred_username"
89 authorize-params: "a=c"
90 auth-style: "header"
91 scopes:
92 - "openid"
93 - "profile"
94 nonce: true
95 pkce: false
96 user-info: true
97 groups-claim: groups_direct
98 refresh:
99 enabled: true
100 expires: 10h0m0s
101 secret: "1jd93h5b6s82lf03jh5b2hf9"
102 use-session-id: true
103 validate-user: true
104 openvpn-username: "token.claims.sub"
105 openvpn:
106 addr: "unix:///run/openvpn/server2.sock"
107 auth-token-user: true
108 auth-pending-timeout: 2m
109 command-timeout: 15s
110 enforce-unique-user: true
111 override-username: true
112 bypass:
113 common-names:
114 - "test"
115 - "test2"
116 client-config:
117 enabled: true
118 ignore-not-found: false
119 path: "."
120 strategy: user-selector
121 expression: |
122 ["default", string(token.claims.sub)]
123 common-name:
124 environment-variable-name: X509_0_emailAddress
125 password: "1jd93h5b6s82lf03jh5b2hf9"
126 pass-through:
127 address: "unix:///run/openvpn/pass-through.sock"
128 enabled: true
129 password: "password"
130 socket-group: "group"
131 socket-mode: "0666"
132 reauthentication: false
133 http:
134 listen: ":9001"
135 secret: "1jd93h5b6s82lf03jh5b2hf9"
136 enable-proxy-headers: false
137 assets-path: "."
138 template: "../../README.md"
139 check:
140 ipaddr: true
141 `,
142 config.Config{
143 Debug: config.Debug{
144 Pprof: true,
145 Listen: ":9002",
146 },
147 Log: config.Log{
148 Format: "json",
149 Level: slog.LevelDebug,
150 VPNClientIP: false,
151 },
152 HTTP: config.HTTP{
153 AssetPath: func() types.FS {
154 dirFS, err := types.NewFS(".")
155 require.NoError(t, err)
156
157 return dirFS
158 }(),
159 BaseURL: types.URL{URL: &url.URL{
160 Scheme: "http",
161 Host: "localhost:9000",
162 }},
163 Check: config.HTTPCheck{
164 IPAddr: true,
165 },
166 EnableProxyHeaders: false,
167 TrustedProxies: types.StringSlice{},
168 Listen: ":9001",
169 Secret: "1jd93h5b6s82lf03jh5b2hf9",
170 Template: func() types.Template {
171 tmpl, err := types.NewTemplate("../../README.md")
172 require.NoError(t, err)
173
174 return tmpl
175 }(),
176 },
177 OpenVPN: config.OpenVPN{
178 Addr: types.URL{URL: &url.URL{
179 Scheme: "unix",
180 Path: "/run/openvpn/server2.sock",
181 OmitHost: false,
182 }},
183 Bypass: config.OpenVPNBypass{
184 CommonNames: types.RegexpSlice{regexp.MustCompile(`^(?:test)$`), regexp.MustCompile(`^(?:test2)$`)},
185 },
186 ClientConfig: config.OpenVPNConfig{
187 Enabled: true,
188 Strategy: config.OpenVPNConfigStrategyUserSelector,
189 Path: func() types.FS {
190 dirFS, err := types.NewFS(".")
191 require.NoError(t, err)
192
193 return dirFS
194 }(),
195 Expression: "[\"default\", string(token.claims.sub)]\n",
196 },
197 Password: "1jd93h5b6s82lf03jh5b2hf9",
198 AuthTokenUser: true,
199 AuthPendingTimeout: 2 * time.Minute,
200 EnforceUniqueUser: true,
201 OverrideUsername: true,
202 CommonName: config.OpenVPNCommonName{
203 EnvironmentVariableName: "X509_0_emailAddress",
204 },
205 Passthrough: config.OpenVPNPassthrough{
206 Enabled: true,
207 Address: types.URL{URL: &url.URL{
208 Scheme: "unix",
209 Path: "/run/openvpn/pass-through.sock",
210 OmitHost: false,
211 }},
212 SocketGroup: "group",
213 SocketMode: types.FileMode(0o666),
214 Password: "password",
215 },
216 CommandTimeout: 15 * time.Second,
217 ReAuthentication: false,
218 },
219 OAuth2: config.OAuth2{
220 Issuer: types.URL{URL: &url.URL{
221 Scheme: "https",
222 Host: "company.zitadel.cloud",
223 }},
224 Provider: "generic",
225 AuthorizeParams: "a=c",
226 Endpoints: config.OAuth2Endpoints{
227 Auth: types.URL{URL: &url.URL{}},
228 Token: types.URL{URL: &url.URL{}},
229 Discovery: types.URL{URL: &url.URL{}},
230 },
231 Client: config.OAuth2Client{
232 ID: "test",
233 Secret: "test",
234 PrivateKeyID: "openvpn-auth-oauth2",
235 },
236 Nonce: true,
237 PKCE: false,
238 UserInfo: true,
239 GroupsClaim: "groups_direct",
240 Scopes: []string{oauth2types.ScopeOpenID, oauth2types.ScopeProfile},
241 AuthStyle: config.OAuth2AuthStyle(oauth2.AuthStyleInHeader),
242 OpenVPNUsername: "token.claims." + testsuite.SubjectClaim,
243 Refresh: config.OAuth2Refresh{
244 Enabled: true,
245 Expires: 10 * time.Hour,
246 Secret: "1jd93h5b6s82lf03jh5b2hf9",
247 UseSessionID: true,
248 ValidateUser: true,
249 },
250 Validate: config.OAuth2Validate{
251 Expression: "openvpn.commonName == token.claims.preferred_username",
252 Groups: []string{"test", "test2"},
253 },
254 },
255 },
256 nil,
257 },
258 } {
259 t.Run(tc.name, func(t *testing.T) {
260 t.Parallel()
261
262 var buf bytes.Buffer
263
264 _ = io.Writer(&buf)
265
266 file, err := os.CreateTemp(t.TempDir(), "openvpn-auth-oauth2-*")
267 require.NoError(t, err)
268
269 // close and remove the temporary file at the end of the program.
270 t.Cleanup(func() {
271 require.NoError(t, file.Close())
272 require.NoError(t, os.Remove(file.Name()))
273 })
274
275 _, err = file.WriteString(tc.configFile)
276 require.NoError(t, err)
277
278 conf, err := config.New([]string{"openvpn-auth-oauth2", "--config", file.Name()}, &buf)
279 if tc.err != nil {
280 require.Error(t, err)
281 assert.Equal(t, tc.err.Error(), err.Error())
282 } else {
283 require.NoError(t, err)
284 assert.Equal(t, tc.conf, *conf)
285 }
286 })
287 }
288 }
289
290 func TestConfigHelpFlag(t *testing.T) {
291 t.Parallel()
292
293 var buf bytes.Buffer
294
295 _ = io.Writer(&buf)
296
297 _, err := config.New([]string{"openvpn-auth-oauth2", "--help"}, &buf)
298
299 require.ErrorIs(t, err, flag.ErrHelp)
300 assert.Contains(t, buf.String(), "--config string")
301 assert.Contains(t, buf.String(), "(env: OPENVPN_AUTH_OAUTH2_CONFIG_FILE)")
302 assert.Contains(t, buf.String(), "(env: OPENVPN_AUTH_OAUTH2_HTTP_LISTEN)")
303 assert.Contains(t, buf.String(), "--openvpn.command-timeout duration")
304 assert.Contains(t, buf.String(), "(env: OPENVPN_AUTH_OAUTH2_OPENVPN_COMMAND_TIMEOUT)")
305 assert.Contains(t, buf.String(), "Possible values: auto, params, header.")
306 assert.Contains(t, buf.String(), "(default params)")
307 assert.Contains(t, buf.String(), "(default /etc/openvpn-auth-oauth2/client-config/)")
308 assert.Contains(t, buf.String(), "--openvpn.pass-through.socket-mode value")
309 assert.Contains(t, buf.String(), "(default 0660)")
310 assert.NotContains(t, buf.String(), "/etc/openvpn-auth-oauth2/client-config-dir/")
311 assert.NotContains(t, buf.String(), "AuthStyleInParams")
312 assert.NotContains(t, buf.String(), "--http.short-url")
313 assert.NotContains(t, buf.String(), "--openvpn.common-name.mode")
314 assert.NotContains(t, buf.String(), "(env: CONFIG_HTTP_LISTEN)")
315 }
316
317 func TestConfigHelpFlagDoesNotExposeSecrets(t *testing.T) {
318 const commandLineSecret = "command-line-secret-marker"
319
320 var buf bytes.Buffer
321
322 t.Setenv("OPENVPN_AUTH_OAUTH2_UNKNOWN", "value")
323
324 _, err := config.New(
325 []string{
326 "openvpn-auth-oauth2",
327 "--config",
328 filepath.Join(t.TempDir(), "missing.yaml"),
329 "--oauth2.client.secret=" + commandLineSecret,
330 "--help",
331 },
332 &buf,
333 )
334
335 require.ErrorIs(t, err, flag.ErrHelp)
336 assert.Contains(t, buf.String(), "Usage of openvpn-auth-oauth2")
337 assert.NotContains(t, buf.String(), commandLineSecret)
338 }
339
340 func TestConfigHelpFlagRedactsLoadedSecrets(t *testing.T) {
341 conf := config.Defaults
342 conf.HTTP.Secret = "http-secret-marker"
343 conf.OpenVPN.Password = "openvpn-secret-marker"
344 conf.OpenVPN.Passthrough.Password = "pass-through-secret-marker"
345 conf.OAuth2.Client.PrivateKey = "private-key-marker"
346 conf.OAuth2.Client.Secret = "oauth2-secret-marker"
347 conf.OAuth2.Refresh.Secret = "refresh-secret-marker"
348
349 t.Setenv("OPENVPN_AUTH_OAUTH2_OAUTH2_CLIENT_SECRET", "environment-secret-marker")
350
351 var buf bytes.Buffer
352
353 err := conf.ReadFromFlagAndEnvironment([]string{"openvpn-auth-oauth2", "--help"}, &buf)
354
355 require.ErrorIs(t, err, flag.ErrHelp)
356
357 for _, secret := range []string{
358 conf.HTTP.Secret.String(),
359 conf.OpenVPN.Password.String(),
360 conf.OpenVPN.Passthrough.Password.String(),
361 conf.OAuth2.Client.PrivateKey.String(),
362 conf.OAuth2.Client.Secret.String(),
363 conf.OAuth2.Refresh.Secret.String(),
364 } {
365 assert.NotContains(t, buf.String(), secret)
366 }
367 }
368
369 func TestConfigFileEnvironmentVariable(t *testing.T) {
370 var buf bytes.Buffer
371
372 configFile, err := os.CreateTemp(t.TempDir(), "openvpn-auth-oauth2-*")
373 require.NoError(t, err)
374
375 _, err = configFile.WriteString("http:\n listen: \":9100\"\n")
376 require.NoError(t, err)
377 require.NoError(t, configFile.Close())
378
379 t.Setenv("OPENVPN_AUTH_OAUTH2_CONFIG_FILE", configFile.Name())
380
381 conf, err := config.New([]string{"openvpn-auth-oauth2"}, &buf)
382 require.NoError(t, err)
383 assert.Equal(t, ":9100", conf.HTTP.Listen)
384 }
385
386 func TestConfigPrecedence(t *testing.T) {
387 var buf bytes.Buffer
388
389 configFile, err := os.CreateTemp(t.TempDir(), "openvpn-auth-oauth2-*")
390 require.NoError(t, err)
391
392 _, err = configFile.WriteString("openvpn:\n command-timeout: 11s\n")
393 require.NoError(t, err)
394 require.NoError(t, configFile.Close())
395
396 t.Setenv("OPENVPN_AUTH_OAUTH2_OPENVPN_COMMAND_TIMEOUT", "12s")
397
398 conf, err := config.New(
399 []string{
400 "openvpn-auth-oauth2",
401 "--config",
402 configFile.Name(),
403 "--openvpn.command-timeout=13s",
404 },
405 &buf,
406 )
407 require.NoError(t, err)
408 assert.Equal(t, 13*time.Second, conf.OpenVPN.CommandTimeout)
409 }
410
411 func TestConfigRejectsRemovedTopLevelConfigProperty(t *testing.T) {
412 t.Parallel()
413
414 var buf bytes.Buffer
415
416 configFile, err := os.CreateTemp(t.TempDir(), "openvpn-auth-oauth2-*")
417 require.NoError(t, err)
418
419 _, err = configFile.WriteString("config: other.yaml\n")
420 require.NoError(t, err)
421 require.NoError(t, configFile.Close())
422
423 _, err = config.New([]string{"openvpn-auth-oauth2", "--config", configFile.Name()}, &buf)
424
425 require.Error(t, err)
426 require.ErrorContains(t, err, "field config not found")
427 }
428
429 func TestConfigRejectsAmbiguousSocketMode(t *testing.T) {
430 t.Parallel()
431
432 for _, tc := range []struct {
433 name string
434 configFile string
435 args []string
436 }{
437 {
438 name: "yaml",
439 configFile: "openvpn:\n pass-through:\n socket-mode: 660\n",
440 },
441 {
442 name: "command line",
443 args: []string{"--openvpn.pass-through.socket-mode=660"},
444 },
445 } {
446 t.Run(tc.name, func(t *testing.T) {
447 t.Parallel()
448
449 var buf bytes.Buffer
450
451 args := slices.Concat([]string{"openvpn-auth-oauth2"}, tc.args)
452 if tc.configFile != "" {
453 configFile, err := os.CreateTemp(t.TempDir(), "openvpn-auth-oauth2-*")
454 require.NoError(t, err)
455
456 _, err = configFile.WriteString(tc.configFile)
457 require.NoError(t, err)
458 require.NoError(t, configFile.Close())
459
460 args = append(args, "--config", configFile.Name())
461 }
462
463 _, err := config.New(args, &buf)
464
465 require.ErrorContains(t, err, "invalid file mode")
466 })
467 }
468 }
469
470 func TestConfigVersionFlag(t *testing.T) {
471 t.Parallel()
472
473 var buf bytes.Buffer
474
475 _ = io.Writer(&buf)
476
477 _, err := config.New(
478 []string{
479 "openvpn-auth-oauth2",
480 "--config",
481 filepath.Join(t.TempDir(), "missing.yaml"),
482 "--version",
483 },
484 &buf,
485 )
486
487 require.ErrorIs(t, err, config.ErrVersion)
488 }
489
490 func TestConfigFlagSet(t *testing.T) {
491 t.Parallel()
492
493 for _, tc := range []struct {
494 name string
495 args []string
496 expectConfig config.Config
497 }{
498 {
499 "--openvpn.bypass.common-names",
500 []string{"--openvpn.bypass.common-names=a,b"},
501 func() config.Config {
502 conf := config.Defaults
503 //goland:noinspection RegExpUnnecessaryNonCapturingGroup
504 conf.OpenVPN.Bypass.CommonNames = types.RegexpSlice{regexp.MustCompile("^(?:a)$"), regexp.MustCompile("^(?:b)$")}
505
506 return conf
507 }(),
508 },
509 {
510 "--oauth2.validate.expression",
511 []string{"--oauth2.validate.expression=openvpn.commonName == token.claims.preferred_username"},
512 func() config.Config {
513 conf := config.Defaults
514 conf.OAuth2.Validate.Expression = "openvpn.commonName == token.claims.preferred_username"
515
516 return conf
517 }(),
518 },
519 {
520 "--http.assets-path",
521 []string{"--http.assets-path=."},
522 func() config.Config {
523 dirFS, err := types.NewFS(".")
524 require.NoError(t, err)
525
526 conf := config.Defaults
527 conf.HTTP.AssetPath = dirFS
528
529 return conf
530 }(),
531 },
532 {
533 "--openvpn.enforce-unique-user",
534 []string{"--openvpn.enforce-unique-user"},
535 func() config.Config {
536 conf := config.Defaults
537 conf.OpenVPN.EnforceUniqueUser = true
538
539 return conf
540 }(),
541 },
542 {
543 "--openvpn.command-timeout",
544 []string{"--openvpn.command-timeout=42s"},
545 func() config.Config {
546 conf := config.Defaults
547 conf.OpenVPN.CommandTimeout = 42 * time.Second
548
549 return conf
550 }(),
551 },
552 {
553 "--openvpn.pass-through.socket-mode",
554 []string{"--openvpn.pass-through.socket-mode=0640"},
555 func() config.Config {
556 conf := config.Defaults
557 conf.OpenVPN.Passthrough.SocketMode = 0o640
558
559 return conf
560 }(),
561 },
562 {
563 "--provider.google.validate.groups-transitive",
564 []string{"--provider.google.validate.groups-transitive"},
565 func() config.Config {
566 conf := config.Defaults
567 conf.Provider.Google.Validate.GroupsTransitive = true
568
569 return conf
570 }(),
571 },
572 } {
573 t.Run(tc.name, func(t *testing.T) {
574 t.Parallel()
575
576 var buf bytes.Buffer
577
578 _ = io.Writer(&buf)
579
580 conf, err := config.New(slices.Concat([]string{"openvpn-auth-oauth2"}, tc.args), &buf)
581
582 require.NoError(t, err)
583 assert.Equal(t, tc.expectConfig, *conf)
584 })
585 }
586 }