-
Notifications
You must be signed in to change notification settings - Fork 42
/
mockoidc.go
273 lines (236 loc) · 7.13 KB
/
mockoidc.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
package mockoidc
import (
"context"
"crypto/rsa"
"crypto/tls"
"errors"
"fmt"
"net"
"net/http"
"time"
)
// NowFunc is an overrideable version of `time.Now`. Tests that need to
// manipulate time can use their own `func() Time` function.
var NowFunc = time.Now
// MockOIDC is a minimal OIDC server for use in OIDC authentication
// integration testing.
type MockOIDC struct {
ClientID string
ClientSecret string
AccessTTL time.Duration
RefreshTTL time.Duration
CodeChallengeMethodsSupported []string
// Normally, these would be private. Expose them publicly for
// power users.
Server *http.Server
Keypair *Keypair
SessionStore *SessionStore
UserQueue *UserQueue
ErrorQueue *ErrorQueue
tlsConfig *tls.Config
middleware []func(http.Handler) http.Handler
fastForward time.Duration
}
// Config gives the various settings MockOIDC starts with that a test
// application server would need to be configured with.
type Config struct {
ClientID string
ClientSecret string
Issuer string
AccessTTL time.Duration
RefreshTTL time.Duration
CodeChallengeMethodsSupported []string
}
// NewServer configures a new MockOIDC that isn't started. An existing
// rsa.PrivateKey can be passed for token signing operations in case
// the default Keypair isn't desired.
func NewServer(key *rsa.PrivateKey) (*MockOIDC, error) {
clientID, err := randomNonce(24)
if err != nil {
return nil, err
}
clientSecret, err := randomNonce(24)
if err != nil {
return nil, err
}
keypair, err := NewKeypair(key)
if err != nil {
return nil, err
}
return &MockOIDC{
ClientID: clientID,
ClientSecret: clientSecret,
AccessTTL: time.Duration(10) * time.Minute,
RefreshTTL: time.Duration(60) * time.Minute,
CodeChallengeMethodsSupported: []string{"plain", "S256"},
Keypair: keypair,
SessionStore: NewSessionStore(),
UserQueue: &UserQueue{},
ErrorQueue: &ErrorQueue{},
}, nil
}
// Run creates a default MockOIDC server and starts it
func Run() (*MockOIDC, error) {
return RunTLS(nil)
}
// RunTLS creates a default MockOIDC server and starts it. It takes a
// tester configured tls.Config for TLS support.
func RunTLS(cfg *tls.Config) (*MockOIDC, error) {
m, err := NewServer(nil)
if err != nil {
return nil, err
}
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
return nil, err
}
return m, m.Start(ln, cfg)
}
// Start starts the MockOIDC server in its own Goroutine on the provided
// net.Listener. In generic `Run`, this defaults to `127.0.0.1:0`
func (m *MockOIDC) Start(ln net.Listener, cfg *tls.Config) error {
if m.Server != nil {
return errors.New("server already started")
}
handler := http.NewServeMux()
handler.Handle(AuthorizationEndpoint, m.chainMiddleware(m.Authorize))
handler.Handle(TokenEndpoint, m.chainMiddleware(m.Token))
handler.Handle(UserinfoEndpoint, m.chainMiddleware(m.Userinfo))
handler.Handle(JWKSEndpoint, m.chainMiddleware(m.JWKS))
handler.Handle(DiscoveryEndpoint, m.chainMiddleware(m.Discovery))
m.Server = &http.Server{
Addr: ln.Addr().String(),
Handler: handler,
TLSConfig: cfg,
}
// Track this to know if we are https
m.tlsConfig = cfg
go func() {
err := m.Server.Serve(ln)
if err != nil && err != http.ErrServerClosed {
panic(err)
}
}()
return nil
}
// Shutdown stops the MockOIDC server. Use this to cleanup test runs.
func (m *MockOIDC) Shutdown() error {
return m.Server.Shutdown(context.Background())
}
func (m *MockOIDC) AddMiddleware(mw func(http.Handler) http.Handler) error {
if m.Server != nil {
return errors.New("server already started")
}
m.middleware = append(m.middleware, mw)
return nil
}
// Config returns the Config with options a connection application or unit
// tests need to be aware of.
func (m *MockOIDC) Config() *Config {
return &Config{
ClientID: m.ClientID,
ClientSecret: m.ClientSecret,
Issuer: m.Issuer(),
CodeChallengeMethodsSupported: m.CodeChallengeMethodsSupported,
AccessTTL: m.AccessTTL,
RefreshTTL: m.RefreshTTL,
}
}
// QueueUser allows adding mock User objects to the authentication queue.
// Calls to the `authorization_endpoint` will pop these mock User objects
// off the queue and create a session with them.
func (m *MockOIDC) QueueUser(user User) {
m.UserQueue.Push(user)
}
// QueueCode allows adding mock code strings to the authentication queue.
// Calls to the `authorization_endpoint` will pop these code strings
// off the queue and create a session with them and return them as the
// code parameter in the response.
func (m *MockOIDC) QueueCode(code string) {
m.SessionStore.CodeQueue.Push(code)
}
// QueueError allows queueing arbitrary errors for the next handler calls
// to return.
func (m *MockOIDC) QueueError(se *ServerError) {
m.ErrorQueue.Push(se)
}
// FastForward moves the MockOIDC's internal view of time forward.
// Use this to test token expirations in your tests.
func (m *MockOIDC) FastForward(d time.Duration) time.Duration {
m.fastForward = m.fastForward + d
return m.fastForward
}
// Now is what MockOIDC thinks time.Now is
func (m *MockOIDC) Now() time.Time {
return NowFunc().Add(m.fastForward)
}
// Addr returns the server address (if started)
func (m *MockOIDC) Addr() string {
if m.Server == nil {
return ""
}
proto := "http"
if m.tlsConfig != nil {
proto = "https"
}
return fmt.Sprintf("%s://%s", proto, m.Server.Addr)
}
// Issuer returns the OIDC Issuer that will be in `iss` token claims
func (m *MockOIDC) Issuer() string {
if m.Server == nil {
return ""
}
return m.Addr() + IssuerBase
}
// DiscoveryEndpoint returns the full `/.well-known/openid-configuration` URL
func (m *MockOIDC) DiscoveryEndpoint() string {
if m.Server == nil {
return ""
}
return m.Addr() + DiscoveryEndpoint
}
// AuthorizationEndpoint returns the OIDC `authorization_endpoint`
func (m *MockOIDC) AuthorizationEndpoint() string {
if m.Server == nil {
return ""
}
return m.Addr() + AuthorizationEndpoint
}
// TokenEndpoint returns the OIDC `token_endpoint`
func (m *MockOIDC) TokenEndpoint() string {
if m.Server == nil {
return ""
}
return m.Addr() + TokenEndpoint
}
// UserinfoEndpoint returns the OIDC `userinfo_endpoint`
func (m *MockOIDC) UserinfoEndpoint() string {
if m.Server == nil {
return ""
}
return m.Addr() + UserinfoEndpoint
}
// JWKSEndpoint returns the OIDC `jwks_uri`
func (m *MockOIDC) JWKSEndpoint() string {
if m.Server == nil {
return ""
}
return m.Addr() + JWKSEndpoint
}
func (m *MockOIDC) chainMiddleware(endpoint func(http.ResponseWriter, *http.Request)) http.Handler {
chain := m.forceError(http.HandlerFunc(endpoint))
for i := len(m.middleware) - 1; i >= 0; i-- {
mw := m.middleware[i]
chain = mw(chain)
}
return chain
}
func (m *MockOIDC) forceError(next http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
if se := m.ErrorQueue.Pop(); se != nil {
errorResponse(rw, se.Error, se.Description, se.Code)
} else {
next.ServeHTTP(rw, req)
}
})
}