forked from jkroepke/openvpn-auth-oauth2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
177 lines (138 loc) · 4.99 KB
/
main.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
package testutils
import (
"bufio"
"crypto/sha256"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/http/cookiejar"
"net/http/httptest"
"net/url"
"strings"
"testing"
"time"
"github.com/jkroepke/openvpn-auth-oauth2/internal/config"
"github.com/jkroepke/openvpn-auth-oauth2/internal/oauth2"
"github.com/jkroepke/openvpn-auth-oauth2/internal/oauth2/providers/generic"
"github.com/jkroepke/openvpn-auth-oauth2/internal/openvpn"
"github.com/jkroepke/openvpn-auth-oauth2/internal/storage"
"github.com/stretchr/testify/require"
oidcStorage "github.com/zitadel/oidc/v3/example/server/storage"
"github.com/zitadel/oidc/v3/pkg/op"
"golang.org/x/text/language"
)
const Secret = "0123456789101112"
func SendLine(tb testing.TB, conn net.Conn, msg string, a ...any) {
tb.Helper()
_, err := fmt.Fprintf(conn, msg, a...)
require.NoError(tb, err)
}
func ReadLine(tb testing.TB, reader *bufio.Reader) string {
tb.Helper()
line, err := reader.ReadString('\n')
if err != nil && !errors.Is(err, io.EOF) {
require.NoError(tb, err)
}
return strings.TrimSpace(line)
}
func SetupResourceServer(tb testing.TB, clientListener net.Listener) (*httptest.Server, *url.URL, config.OAuth2Client, error) {
tb.Helper()
client := oidcStorage.WebClient(
clientListener.Addr().String(),
"SECRET",
fmt.Sprintf("http://%s/oauth2/callback", clientListener.Addr().String()),
)
clients := map[string]*oidcStorage.Client{
clientListener.Addr().String(): client,
}
opStorage := oidcStorage.NewStorageWithClients(oidcStorage.NewUserStore("http://localhost"), clients)
opConfig := &op.Config{
CryptoKey: sha256.Sum256([]byte("test")),
DefaultLogoutRedirectURI: "/",
CodeMethodS256: true,
AuthMethodPost: true,
AuthMethodPrivateKeyJWT: true,
GrantTypeRefreshToken: true,
RequestObjectSupported: true,
SupportedUILocales: []language.Tag{language.English},
}
opProvider, err := op.NewProvider(opConfig, opStorage, op.IssuerFromHost(""), op.WithAllowInsecure())
if err != nil {
return nil, nil, config.OAuth2Client{}, err //nolint:wrapcheck
}
mux := http.NewServeMux()
mux.Handle("/", opProvider)
mux.Handle("/login/username", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_ = opStorage.CheckUsernamePassword("test-user@localhost", "verysecure", r.FormValue("authRequestID"))
http.Redirect(w, r, op.AuthCallbackURL(opProvider)(r.Context(), r.FormValue("authRequestID")), http.StatusFound)
}))
resourceServer := httptest.NewServer(mux)
resourceServerURL, err := url.Parse(resourceServer.URL)
if err != nil {
return nil, nil, config.OAuth2Client{}, err //nolint:wrapcheck
}
return resourceServer, resourceServerURL, config.OAuth2Client{ID: clientListener.Addr().String(), Secret: "SECRET"}, nil
}
// SetupMockEnvironment setups an OpenVPN and IDP mock
//
//nolint:cyclop
func SetupMockEnvironment(tb testing.TB, conf config.Config) (config.Config, *openvpn.Client, net.Listener,
*oauth2.Provider, *httptest.Server, *http.Client, *Logger, func(),
) {
tb.Helper()
logger := NewTestLogger()
managementInterface := TCPTestListener(tb)
clientListener := TCPTestListener(tb)
resourceServer, resourceServerURL, clientCredentials, err := SetupResourceServer(tb, clientListener)
require.NoError(tb, err)
if conf.HTTP.BaseURL == nil {
conf.HTTP.BaseURL = &url.URL{Scheme: "http", Host: clientListener.Addr().String()}
}
if conf.HTTP.Secret == "" {
conf.HTTP.Secret = Secret
}
if conf.HTTP.CallbackTemplate == nil {
conf.HTTP.CallbackTemplate = config.Defaults.HTTP.CallbackTemplate
}
if conf.OpenVpn.Addr == nil {
conf.OpenVpn.Addr = &url.URL{Scheme: managementInterface.Addr().Network(), Host: managementInterface.Addr().String()}
}
if conf.OpenVpn.Bypass.CommonNames == nil {
conf.OpenVpn.Bypass.CommonNames = make([]string, 0)
}
if conf.OAuth2.Issuer == nil {
conf.OAuth2.Issuer = resourceServerURL
}
if conf.OAuth2.Provider == "" {
conf.OAuth2.Provider = generic.Name
}
if conf.OAuth2.Client.ID == "" {
conf.OAuth2.Client.ID = clientCredentials.ID
}
if conf.OAuth2.Client.Secret.String() == "" {
conf.OAuth2.Client.Secret = clientCredentials.Secret
}
if conf.OAuth2.Refresh.Expires.String() == "" {
conf.OAuth2.Refresh.Expires = time.Hour
}
storageClient := storage.New(Secret, conf.OAuth2.Refresh.Expires)
provider := oauth2.New(logger.Logger, conf, storageClient)
openvpnClient := openvpn.NewClient(logger.Logger, conf, provider)
require.NoError(tb, provider.Initialize(openvpnClient))
httpClientListener := httptest.NewUnstartedServer(provider.Handler())
httpClientListener.Listener.Close()
httpClientListener.Listener = clientListener
httpClientListener.Start()
httpClient := httpClientListener.Client()
jar, err := cookiejar.New(nil)
require.NoError(tb, err)
httpClient.Jar = jar
return conf, openvpnClient, managementInterface, provider, httpClientListener, httpClient, logger, func() {
defer managementInterface.Close()
defer clientListener.Close()
defer resourceServer.Close()
defer httpClientListener.Close()
}
}