-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
moderated_sessions_test.go
433 lines (402 loc) · 12.9 KB
/
moderated_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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
/*
Copyright 2022 Gravitational, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package proxy
import (
"context"
"errors"
"fmt"
"io"
"net/http"
"regexp"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/gravitational/trace"
"github.com/stretchr/testify/require"
"golang.org/x/sync/errgroup"
"k8s.io/client-go/tools/remotecommand"
"github.com/gravitational/teleport/api/types"
apievents "github.com/gravitational/teleport/api/types/events"
"github.com/gravitational/teleport/lib/events"
testingkubemock "github.com/gravitational/teleport/lib/kube/proxy/testing/kube_server"
"github.com/gravitational/teleport/lib/modules"
)
func TestModeratedSessions(t *testing.T) {
// enable enterprise features to have access to ModeratedSessions.
modules.SetTestModules(t, &modules.TestModules{TestBuildType: modules.BuildEnterprise})
const (
moderatorUsername = "moderator_user"
moderatorRoleName = "mod_role"
userRequiringModeration = "user_wmod"
roleRequiringModeration = "role_wmod"
stdinPayload = "sessionPayload"
discardPayload = "discardPayload"
exitKeyword = "exit"
)
var (
// numSessionEndEvents represents the number of session.end events received
// from audit events.
numSessionEndEvents = new(int64)
// numberOfExpectedSessionEnds is the number of session ends expected from
// all tests. This value is incremented each time that a test has
// tt.want.sessionEndEvent = true.
numberOfExpectedSessionEnds int64
)
// kubeMock is a Kubernetes API mock for the session tests.
// Once a new session is created, this mock will write to
// stdout and stdin (if available) the pod name, followed
// by copying the contents of stdin into both streams.
kubeMock, err := testingkubemock.NewKubeAPIMock()
require.NoError(t, err)
t.Cleanup(func() { kubeMock.Close() })
// creates a Kubernetes service with a configured cluster pointing to mock api server
testCtx := SetupTestContext(
context.Background(),
t,
TestConfig{
Clusters: []KubeClusterConfig{{Name: kubeCluster, APIEndpoint: kubeMock.URL}},
// onEvent is called each time a new event is produced. We only care about
// sessionEnd events.
OnEvent: func(ae apievents.AuditEvent) {
if ae.GetType() == events.SessionEndEvent {
atomic.AddInt64(numSessionEndEvents, 1)
}
},
},
)
// close tests
t.Cleanup(func() { require.NoError(t, testCtx.Close()) })
t.Cleanup(func() {
// Set a cleanup function to make sure it runs after every test completes.
// It will validate if the # of session ends is the same as expected
// number of session ends.
require.Eventually(t, func() bool {
// checks if the # of session ends is the same as expected
// number of session ends.
return atomic.LoadInt64(numSessionEndEvents) == numberOfExpectedSessionEnds
}, 20*time.Second, 500*time.Millisecond)
})
// create a user with access to kubernetes that does not require any moderator.
// (kubernetes_user and kubernetes_groups specified)
user, _ := testCtx.CreateUserAndRole(
testCtx.Context,
t,
username,
RoleSpec{
Name: roleName,
KubeUsers: roleKubeUsers,
KubeGroups: roleKubeGroups,
})
// create a moderator user with access to kubernetes
// (kubernetes_user and kubernetes_groups specified)
moderator, modRole := testCtx.CreateUserAndRole(
testCtx.Context,
t,
moderatorUsername,
RoleSpec{
Name: moderatorRoleName,
// sessionJoin:
SessionJoin: []*types.SessionJoinPolicy{
{
Name: "Auditor oversight",
Roles: []string{"*"},
Kinds: []string{"k8s"},
Modes: []string{string(types.SessionModeratorMode)},
},
},
SetupRoleFunc: func(r types.Role) {
// set kubernetes labels to empty to test relaxed join rules
r.SetKubernetesLabels(types.Allow, types.Labels{})
},
})
// create a userRequiringModerator with access to kubernetes thar requires
// one moderator to join the session.
userRequiringModerator, _ := testCtx.CreateUserAndRole(
testCtx.Context,
t,
userRequiringModeration,
RoleSpec{
Name: roleRequiringModeration,
KubeUsers: roleKubeUsers,
KubeGroups: roleKubeGroups,
SessionRequire: []*types.SessionRequirePolicy{
{
Name: "Auditor oversight",
Filter: fmt.Sprintf("contains(user.spec.roles, %q)", modRole.GetName()),
Kinds: []string{"k8s"},
Modes: []string{string(types.SessionModeratorMode)},
Count: 1,
},
},
})
type args struct {
user types.User
moderator types.User
closeSession bool
moderatorForcedClose bool
}
type want struct {
sessionEndEvent bool
}
tests := []struct {
name string
args args
want want
}{
{
name: "create session for user without moderation",
args: args{
user: user,
},
want: want{
sessionEndEvent: true,
},
},
{
name: "create session with moderation",
args: args{
user: userRequiringModerator,
moderator: moderator,
},
want: want{
sessionEndEvent: true,
},
},
{
name: "create session without needing moderation but leave it without proper closing",
args: args{
user: user,
closeSession: true,
},
want: want{
sessionEndEvent: true,
},
},
{
name: "create session with moderation but close connection before moderator joined",
args: args{
user: userRequiringModerator,
closeSession: true,
},
want: want{
// until moderator joins the session is not started. If the connection
// is closed, Teleport does not create any start or end events.
sessionEndEvent: false,
},
},
{
name: "create session with moderation and once the session is active, the moderator closes it",
args: args{
user: userRequiringModerator,
moderator: moderator,
moderatorForcedClose: true,
},
want: want{
sessionEndEvent: true,
},
},
}
for _, tt := range tests {
tt := tt
if tt.want.sessionEndEvent {
numberOfExpectedSessionEnds++
}
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
group := &errgroup.Group{}
// generate a kube client with user certs for auth
_, config := testCtx.GenTestKubeClientTLSCert(
t,
tt.args.user.GetName(),
kubeCluster,
)
// create a user session.
var (
stdinReader, stdinWritter = io.Pipe()
stdoutReader, stdoutWritter = io.Pipe()
)
streamOpts := remotecommand.StreamOptions{
Stdin: stdinReader,
Stdout: stdoutWritter,
// when Tty is enabled, Stderr must be nil.
Stderr: nil,
Tty: true,
}
req, err := generateExecRequest(
testCtx.KubeServiceAddress(),
podName,
podNamespace,
podContainerName,
containerCommmandExecute, // placeholder for commands to execute in the dummy pod
streamOpts,
)
require.NoError(t, err)
exec, err := remotecommand.NewSPDYExecutor(config, http.MethodPost, req.URL())
require.NoError(t, err)
// sessionIDC is used to share the sessionID between the user exec request and
// the moderator. Once the moderator receives it, he can join the session.
sessionIDC := make(chan string, 1)
// moderatorJoined is used to syncronize when the moderator joins the session.
moderatorJoined := make(chan struct{})
once := sync.Once{}
if tt.args.moderator != nil {
// generate moderator certs
_, config := testCtx.GenTestKubeClientTLSCert(
t,
tt.args.moderator.GetName(),
kubeCluster,
)
// Simulate a moderator joining the session.
group.Go(func() error {
// waits for user to send the sessionID of his exec request.
sessionID := <-sessionIDC
t.Logf("moderator is joining sessionID %q", sessionID)
// join the session.
stream, err := testCtx.NewJoiningSession(config, sessionID, types.SessionModeratorMode)
if err != nil {
return trace.Wrap(err)
}
t.Cleanup(func() {
require.NoError(t, stream.Close())
})
// always send the force terminate even when the session is normally closed.
defer func() {
stream.ForceTerminate()
}()
// moderator waits for the user informed that he joined the session.
<-moderatorJoined
for {
p := make([]byte, 1024)
n, err := stream.Read(p)
if err != nil {
return trace.Wrap(err)
}
stringData := string(p[:n])
// discardPayload is sent before the moderator joined the session.
// If the moderator sees it, it means that the payload was not correctly
// discarded.
if strings.Contains(stringData, discardPayload) {
return trace.Wrap(errors.New("discardPayload was not properly discarded"))
}
// stdinPayload is sent by the user after the session started.
if strings.Contains(stringData, stdinPayload) {
break
}
// podContainerName is returned by the kubemock server and it's used
// to control that the session has effectively started.
// return to force the defer to run.
if strings.Contains(stringData, podContainerName) && tt.args.moderatorForcedClose {
return nil
}
}
return nil
})
}
// Simulate a user creating a session.
group.Go(func() (err error) {
// sessionIDRegex is used to parse the sessionID from the payload sent
// to the user when moderation is needed
sessionIDRegex := regexp.MustCompile(`(?m)ID: (.*)\.\.\.`)
// identifiedData is used to control if the stdin data was correctly
// received from the session TermManager.
identifiedData := false
defer func() {
// close pipes.
stdinWritter.Close()
stdoutReader.Close()
// validate if the data payload was received.
// When force closing (user or moderator) we do not expect identifiedData
// to be true.
if err == nil && !identifiedData && !tt.args.closeSession && !tt.args.moderatorForcedClose {
err = errors.New("data payload was not identified")
}
}()
for {
data := make([]byte, 1024)
n, err := stdoutReader.Read(data)
// ignore EOF and ErrClosedPipe errors
if errors.Is(err, io.EOF) || errors.Is(err, io.ErrClosedPipe) {
return nil
} else if err != nil {
return trace.Wrap(err)
}
if tt.args.closeSession {
return nil
}
stringData := string(data[:n])
if sessionIDRegex.MatchString(stringData) {
matches := sessionIDRegex.FindAllStringSubmatch(stringData, -1)
sessionID := matches[0][1]
t.Logf("sessionID identified %q", sessionID)
// if sessionID is identified it means that the user waits for
// a moderator to join. In the meanwhile we write to stdin to make sure it's
// discarded.
_, err := stdinWritter.Write([]byte(discardPayload))
if err != nil {
return trace.Wrap(err)
}
// send sessionID to moderator.
sessionIDC <- sessionID
}
// checks if moderator has joined the session.
// Each time a user joins a session the following message is broadcasted
// User <user> joined the session.
if strings.Contains(stringData, fmt.Sprintf("User %s joined the session.", moderatorUsername)) {
t.Logf("identified that moderator joined the session")
// inform moderator goroutine that the user detected that he joined the
// session.
once.Do(func() {
close(moderatorJoined)
})
}
// if podContainerName is received, it means the session has already reached
// the mock server. If we expect the moderated to force close the session
// we don't send the stdinPayload data and the session will remain active.
if strings.Contains(stringData, podContainerName) && !tt.args.moderatorForcedClose {
// successfully connected to
_, err := stdinWritter.Write([]byte(stdinPayload))
if err != nil {
return trace.Wrap(err)
}
}
// check if we received the data we wrote into the stdin pipe.
if strings.Contains(stringData, stdinPayload) {
t.Logf("received the payload written to stdin")
identifiedData = true
break
}
}
return nil
},
)
group.Go(func() error {
defer func() {
// once stream is finished close the pipes.
stdinReader.Close()
stdoutWritter.Close()
}()
// start user session.
err := exec.StreamWithContext(testCtx.Context, streamOpts)
// ignore closed pipes error.
if errors.Is(err, io.ErrClosedPipe) {
return nil
}
return trace.Wrap(err)
})
// wait for every go-routine to finish without errors returned.
require.NoError(t, group.Wait())
})
}
}