forked from gravitational/teleport
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsessions_test.go
274 lines (230 loc) · 7.96 KB
/
sessions_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
/*
* Teleport
* Copyright (C) 2023 Gravitational, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package web
import (
"context"
"errors"
"sync/atomic"
"testing"
"time"
"github.com/google/uuid"
"github.com/gravitational/trace"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/gravitational/teleport/api/types"
"github.com/gravitational/teleport/lib/auth"
"github.com/gravitational/teleport/lib/modules"
"github.com/gravitational/teleport/lib/reversetunnelclient"
"github.com/gravitational/teleport/lib/utils"
"github.com/gravitational/teleport/lib/utils/cert"
)
func TestRemoteClientCache(t *testing.T) {
t.Parallel()
var openCount atomic.Int32
cache := remoteClientCache{}
sa1 := newMockRemoteSite("a")
sa2 := newMockRemoteSite("a")
sb := newMockRemoteSite("b")
err1 := errors.New("c1")
err2 := errors.New("c2")
require.NoError(t, cache.addRemoteClient(sa1, newMockClientI(&openCount, err1)))
require.Equal(t, int32(1), openCount.Load())
require.ErrorIs(t, cache.addRemoteClient(sa2, newMockClientI(&openCount, nil)), err1)
require.Equal(t, int32(1), openCount.Load())
require.NoError(t, cache.addRemoteClient(sb, newMockClientI(&openCount, err2)))
require.Equal(t, int32(2), openCount.Load())
var aggrErr trace.Aggregate
require.ErrorAs(t, cache.Close(), &aggrErr)
require.ElementsMatch(t, []error{err2}, aggrErr.Errors())
require.Zero(t, openCount.Load())
}
func newMockRemoteSite(name string) reversetunnelclient.RemoteSite {
return &mockRemoteSite{name: name}
}
type mockRemoteSite struct {
reversetunnelclient.RemoteSite
name string
}
func (m *mockRemoteSite) GetName() string {
return m.name
}
func newMockClientI(openCount *atomic.Int32, closeErr error) auth.ClientI {
openCount.Add(1)
return &mockClientI{openCount: openCount, closeErr: closeErr}
}
type mockClientI struct {
auth.ClientI
openCount *atomic.Int32
closeErr error
}
func (m *mockClientI) Close() error {
m.openCount.Add(-1)
return m.closeErr
}
func (m *mockClientI) GetDomainName(ctx context.Context) (string, error) {
return "test", nil
}
func TestGetUserClient(t *testing.T) {
t.Parallel()
ctx := context.Background()
var openCount atomic.Int32
sctx := SessionContext{
cfg: SessionContextConfig{
RootClusterName: "local",
newRemoteClient: func(ctx context.Context, sessionContext *SessionContext, site reversetunnelclient.RemoteSite) (auth.ClientI, error) {
return newMockClientI(&openCount, nil), nil
},
},
}
localSite := &mockRemoteSite{name: "local"}
remoteSite := &mockRemoteSite{name: "remote"}
// getting a client for the local site should return
// the RootClient from SessionContextConfig
clt, err := sctx.GetUserClient(ctx, localSite)
require.NoError(t, err)
require.Nil(t, clt)
require.Zero(t, openCount.Load())
// getting a client a remote site for the first time
// should call newRemoteClient from SessionContextConfig
// and increment openCount
clt, err = sctx.GetUserClient(ctx, remoteSite)
require.NoError(t, err)
require.NotNil(t, clt)
require.Equal(t, int32(1), openCount.Load())
// getting a client a remote site a second time
// should return the cached client and not call
// newRemoteClient from SessionContextConfig
clt, err = sctx.GetUserClient(ctx, remoteSite)
require.NoError(t, err)
require.NotNil(t, clt)
require.Equal(t, int32(1), openCount.Load())
// clear the remote cache
require.NoError(t, sctx.remoteClientCache.Close())
require.Zero(t, openCount.Load())
// now attempt to get the same remote site concurrently
// and ensure that the first request creates the client
// and the second request is provided the cached value
type result struct {
clt auth.ClientI
err error
}
resultCh := make(chan result, 2)
go func() {
clt, err := sctx.GetUserClient(ctx, remoteSite)
resultCh <- result{clt: clt, err: err}
}()
go func() {
clt, err := sctx.GetUserClient(ctx, remoteSite)
resultCh <- result{clt: clt, err: err}
}()
timeout := time.After(10 * time.Second)
clients := make([]auth.ClientI, 2)
for i := 0; i < 2; i++ {
select {
case res := <-resultCh:
require.NoError(t, res.err)
require.NotNil(t, res.clt)
clients[i] = res.clt
case <-timeout:
t.Fatalf("Timed out waiting for user client results")
}
}
// ensure that only one client was created and that
// both clients returned are functional
require.Equal(t, int32(1), openCount.Load())
for i := 0; i < 2; i++ {
domain, err := clients[i].GetDomainName(ctx)
require.NoError(t, err)
require.Equal(t, "test", domain)
}
}
func TestSessionCache_watcher(t *testing.T) {
// Can't t.Parallel because of modules.SetTestModules.
// Requires Enterprise to work.
modules.SetTestModules(t, &modules.TestModules{
TestBuildType: modules.BuildEnterprise,
})
webSuite := newWebSuite(t)
authServer := webSuite.server.AuthServer.AuthServer
authClient := webSuite.proxyClient
clock := webSuite.clock
// cancel is used to make sure the sessionCache stops cleanly.
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
sessionCache, err := newSessionCache(ctx, sessionCacheOptions{
proxyClient: authClient,
accessPoint: authClient,
servers: []utils.NetAddr{
// An addr is required but unused.
{Addr: "localhost:12345", AddrNetwork: "tcp"}},
clock: clock,
sessionLingeringThreshold: 1 * time.Minute,
startWebSessionWatcherImmediately: true,
})
require.NoError(t, err, "newSessionCache() failed")
defer sessionCache.Close()
// Sanity check active sessions.
require.Zero(t,
sessionCache.ActiveSessions(),
"ActiveSessions() count mismatch")
// Create realistic keys and certificates, newSessionContextFromSession
// requires it.
creds, err := cert.GenerateSelfSignedCert(nil /* hostNames */, nil /* ipAddresses */)
require.NoError(t, err, "GenerateSelfSignedCert() failed")
// Create a new "fake" session. We'll update it later and see if the watcher
// is triggered.
sessionID := uuid.NewString()
expires := clock.Now().Add(1 * time.Hour)
session, err := types.NewWebSession(sessionID, types.KindWebSession, types.WebSessionSpecV2{
User: "llama", // fake
Pub: []byte(`ceci n'est pas an SSH certificate`),
Priv: creds.PrivateKey,
TLSCert: creds.Cert,
BearerToken: "12345678",
BearerTokenExpires: expires,
Expires: expires,
IdleTimeout: types.Duration(1 * time.Hour),
})
require.NoError(t, err, "NewWebSession() failed")
// Record session in cache.
_, err = sessionCache.newSessionContextFromSession(ctx, session)
require.NoError(t, err, "newSessionContextFromSession() failed")
// Sanity check active sessions.
require.Equal(t,
1,
sessionCache.ActiveSessions(),
"ActiveSessions() count mismatch")
// An update should cause the cache to evict the session.
// Certs here don't need to be realistic, they are never parsed.
sessionV2 := session.(*types.WebSessionV2)
sessionV2.Spec.Pub = []byte(`new SSH certificate`)
sessionV2.Spec.TLSCert = []byte(`new X.509 certificate`)
require.NoError(t,
authServer.WebSessions().Upsert(ctx, sessionV2),
"WebSessions.Upsert() failed",
)
// Verify that the session was evicted from the cache.
assert.Eventually(t,
func() bool {
return sessionCache.ActiveSessions() == 0
},
2*time.Second, /* waitTime */
100*time.Millisecond, /* tick */
"sessionCache not evicted before timeout",
)
}