File: session_manager.go

package info (click to toggle)
golang-github-vmware-govmomi 0.24.2-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 11,848 kB
  • sloc: sh: 2,285; lisp: 1,560; ruby: 948; xml: 139; makefile: 54
file content (462 lines) | stat: -rw-r--r-- 11,657 bytes parent folder | download | duplicates (2)
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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
/*
Copyright (c) 2017-2018 VMware, Inc. All Rights Reserved.

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 simulator

import (
	"context"
	"fmt"
	"net/http"
	"os"
	"reflect"
	"strings"
	"sync"
	"time"

	"github.com/google/uuid"
	"github.com/vmware/govmomi/session"
	"github.com/vmware/govmomi/vim25/methods"
	"github.com/vmware/govmomi/vim25/mo"
	"github.com/vmware/govmomi/vim25/soap"
	"github.com/vmware/govmomi/vim25/types"
)

type SessionManager struct {
	mo.SessionManager
	nopLocker

	ServiceHostName string
	TLSCert         func() string

	sessions map[string]Session
}

func (m *SessionManager) init(*Registry) {
	m.sessions = make(map[string]Session)
}

var (
	// SessionIdleTimeout duration used to expire idle sessions
	SessionIdleTimeout time.Duration

	sessionMutex sync.Mutex

	// secureCookies enables Set-Cookie.Secure=true
	// We can't do this by default as simulator.Service defaults to no TLS by default and
	// Go's cookiejar does not send Secure cookies unless the URL scheme is https.
	secureCookies = os.Getenv("VCSIM_SECURE_COOKIES") == "true"
)

func createSession(ctx *Context, name string, locale string) types.UserSession {
	now := time.Now().UTC()

	if locale == "" {
		locale = session.Locale
	}

	session := Session{
		UserSession: types.UserSession{
			Key:              uuid.New().String(),
			UserName:         name,
			FullName:         name,
			LoginTime:        now,
			LastActiveTime:   now,
			Locale:           locale,
			MessageLocale:    locale,
			ExtensionSession: types.NewBool(false),
		},
		Registry: NewRegistry(),
	}

	ctx.SetSession(session, true)

	return ctx.Session.UserSession
}

func (m *SessionManager) getSession(id string) (Session, bool) {
	sessionMutex.Lock()
	defer sessionMutex.Unlock()
	s, ok := m.sessions[id]
	return s, ok
}

func (m *SessionManager) delSession(id string) {
	sessionMutex.Lock()
	defer sessionMutex.Unlock()
	delete(m.sessions, id)
}

func (m *SessionManager) putSession(s Session) {
	sessionMutex.Lock()
	defer sessionMutex.Unlock()
	m.sessions[s.Key] = s
}

func (s *SessionManager) validLogin(ctx *Context, req *types.Login) bool {
	if ctx.Session != nil {
		return false
	}
	user := ctx.svc.Listen.User
	if user == nil || user == DefaultLogin {
		return req.UserName != "" && req.Password != ""
	}
	pass, _ := user.Password()
	return req.UserName == user.Username() && req.Password == pass
}

func (s *SessionManager) Login(ctx *Context, req *types.Login) soap.HasFault {
	body := new(methods.LoginBody)

	if s.validLogin(ctx, req) {
		body.Res = &types.LoginResponse{
			Returnval: createSession(ctx, req.UserName, req.Locale),
		}
	} else {
		body.Fault_ = invalidLogin
	}

	return body
}

func (s *SessionManager) LoginExtensionByCertificate(ctx *Context, req *types.LoginExtensionByCertificate) soap.HasFault {
	body := new(methods.LoginExtensionByCertificateBody)

	if ctx.req.TLS == nil || len(ctx.req.TLS.PeerCertificates) == 0 {
		body.Fault_ = Fault("", new(types.NoClientCertificate))
		return body
	}

	if req.ExtensionKey == "" || ctx.Session != nil {
		body.Fault_ = invalidLogin
	} else {
		body.Res = &types.LoginExtensionByCertificateResponse{
			Returnval: createSession(ctx, req.ExtensionKey, req.Locale),
		}
	}

	return body
}

func (s *SessionManager) LoginByToken(ctx *Context, req *types.LoginByToken) soap.HasFault {
	body := new(methods.LoginByTokenBody)

	if ctx.Session != nil {
		body.Fault_ = invalidLogin
	} else {
		var subject struct {
			ID string `xml:"Assertion>Subject>NameID"`
		}

		if s, ok := ctx.Header.Security.(*Element); ok {
			_ = s.Decode(&subject)
		}

		if subject.ID == "" {
			body.Fault_ = invalidLogin
			return body
		}

		body.Res = &types.LoginByTokenResponse{
			Returnval: createSession(ctx, subject.ID, req.Locale),
		}
	}

	return body
}

func (s *SessionManager) Logout(ctx *Context, _ *types.Logout) soap.HasFault {
	session := ctx.Session
	s.delSession(session.Key)
	pc := Map.content().PropertyCollector

	for ref, obj := range ctx.Session.Registry.objects {
		if ref == pc {
			continue // don't unregister the PropertyCollector singleton
		}
		if _, ok := obj.(RegisterObject); ok {
			ctx.Map.Remove(ref) // Remove RegisterObject handlers
		}
	}

	ctx.postEvent(&types.UserLogoutSessionEvent{
		IpAddress: session.IpAddress,
		UserAgent: session.UserAgent,
		SessionId: session.Key,
		LoginTime: &session.LoginTime,
	})

	return &methods.LogoutBody{Res: new(types.LogoutResponse)}
}

func (s *SessionManager) TerminateSession(ctx *Context, req *types.TerminateSession) soap.HasFault {
	body := new(methods.TerminateSessionBody)

	for _, id := range req.SessionId {
		if id == ctx.Session.Key {
			body.Fault_ = Fault("", new(types.InvalidArgument))
			return body
		}
		if _, ok := s.getSession(id); !ok {
			body.Fault_ = Fault("", new(types.NotFound))
			return body
		}
		s.delSession(id)
	}

	body.Res = new(types.TerminateSessionResponse)
	return body
}

func (s *SessionManager) SessionIsActive(ctx *Context, req *types.SessionIsActive) soap.HasFault {
	body := new(methods.SessionIsActiveBody)

	if ctx.Map.IsESX() {
		body.Fault_ = Fault("", new(types.NotImplemented))
		return body
	}

	body.Res = new(types.SessionIsActiveResponse)

	if session, exists := s.getSession(req.SessionID); exists {
		body.Res.Returnval = session.UserName == req.UserName
	}

	return body
}

func (s *SessionManager) AcquireCloneTicket(ctx *Context, _ *types.AcquireCloneTicket) soap.HasFault {
	session := *ctx.Session
	session.Key = uuid.New().String()
	s.putSession(session)

	return &methods.AcquireCloneTicketBody{
		Res: &types.AcquireCloneTicketResponse{
			Returnval: session.Key,
		},
	}
}

func (s *SessionManager) CloneSession(ctx *Context, ticket *types.CloneSession) soap.HasFault {
	body := new(methods.CloneSessionBody)

	session, exists := s.getSession(ticket.CloneTicket)

	if exists {
		s.delSession(ticket.CloneTicket) // A clone ticket can only be used once
		session.Key = uuid.New().String()
		ctx.SetSession(session, true)

		body.Res = &types.CloneSessionResponse{
			Returnval: session.UserSession,
		}
	} else {
		body.Fault_ = invalidLogin
	}

	return body
}

func (s *SessionManager) AcquireGenericServiceTicket(ticket *types.AcquireGenericServiceTicket) soap.HasFault {
	return &methods.AcquireGenericServiceTicketBody{
		Res: &types.AcquireGenericServiceTicketResponse{
			Returnval: types.SessionManagerGenericServiceTicket{
				Id:       uuid.New().String(),
				HostName: s.ServiceHostName,
			},
		},
	}
}

// internalContext is the session for use by the in-memory client (Service.RoundTrip)
var internalContext = &Context{
	Context: context.Background(),
	Session: &Session{
		UserSession: types.UserSession{
			Key: uuid.New().String(),
		},
		Registry: NewRegistry(),
	},
	Map: Map,
}

var invalidLogin = Fault("Login failure", new(types.InvalidLogin))

// Context provides per-request Session management.
type Context struct {
	req *http.Request
	res http.ResponseWriter
	svc *Service

	context.Context
	Session *Session
	Header  soap.Header
	Caller  *types.ManagedObjectReference
	Map     *Registry
}

// mapSession maps an HTTP cookie to a Session.
func (c *Context) mapSession() {
	if cookie, err := c.req.Cookie(soap.SessionCookieName); err == nil {
		if val, ok := c.svc.sm.getSession(cookie.Value); ok {
			c.SetSession(val, false)
		}
	}
}

func (m *SessionManager) expiredSession(id string, now time.Time) bool {
	expired := true

	s, ok := m.getSession(id)
	if ok {
		expired = now.Sub(s.LastActiveTime) > SessionIdleTimeout
		if expired {
			m.delSession(id)
		}
	}

	return expired
}

// SessionIdleWatch starts a goroutine that calls func expired() at SessionIdleTimeout intervals.
// The goroutine exits if the func returns true.
func SessionIdleWatch(ctx context.Context, id string, expired func(string, time.Time) bool) {
	if SessionIdleTimeout == 0 {
		return
	}

	go func() {
		for t := time.NewTimer(SessionIdleTimeout); ; {
			select {
			case <-ctx.Done():
				return
			case now := <-t.C:
				if expired(id, now) {
					return
				}
				t.Reset(SessionIdleTimeout)
			}
		}
	}()
}

// SetSession should be called after successful authentication.
func (c *Context) SetSession(session Session, login bool) {
	session.UserAgent = c.req.UserAgent()
	session.IpAddress = strings.Split(c.req.RemoteAddr, ":")[0]
	session.LastActiveTime = time.Now()
	session.CallCount++

	c.svc.sm.putSession(session)
	c.Session = &session

	if login {
		http.SetCookie(c.res, &http.Cookie{
			Name:     soap.SessionCookieName,
			Value:    session.Key,
			Secure:   secureCookies,
			HttpOnly: true,
		})

		c.postEvent(&types.UserLoginSessionEvent{
			SessionId: session.Key,
			IpAddress: session.IpAddress,
			UserAgent: session.UserAgent,
			Locale:    session.Locale,
		})

		SessionIdleWatch(c.Context, session.Key, c.svc.sm.expiredSession)
	}
}

// WithLock holds a lock for the given object while then given function is run.
func (c *Context) WithLock(obj mo.Reference, f func()) {
	if c.Caller != nil && *c.Caller == obj.Reference() {
		// Internal method invocation, obj is already locked
		f()
		return
	}
	Map.WithLock(obj, f)
}

// postEvent wraps EventManager.PostEvent for internal use, with a lock on the EventManager.
func (c *Context) postEvent(events ...types.BaseEvent) {
	m := Map.EventManager()
	c.WithLock(m, func() {
		for _, event := range events {
			m.PostEvent(c, &types.PostEvent{EventToPost: event})
		}
	})
}

// Session combines a UserSession and a Registry for per-session managed objects.
type Session struct {
	types.UserSession
	*Registry
}

func (s *Session) setReference(item mo.Reference) {
	ref := item.Reference()
	if ref.Value == "" {
		ref.Value = fmt.Sprintf("session[%s]%s", s.Key, uuid.New())
	}
	if ref.Type == "" {
		ref.Type = typeName(item)
	}
	s.Registry.setReference(item, ref)
}

// Put wraps Registry.Put, setting the moref value to include the session key.
func (s *Session) Put(item mo.Reference) mo.Reference {
	s.setReference(item)
	return s.Registry.Put(item)
}

// Get wraps Registry.Get, session-izing singleton objects such as SessionManager and the root PropertyCollector.
func (s *Session) Get(ref types.ManagedObjectReference) mo.Reference {
	obj := s.Registry.Get(ref)
	if obj != nil {
		return obj
	}

	// Return a session "view" of certain singleton objects
	switch ref.Type {
	case "SessionManager":
		// Clone SessionManager so the PropertyCollector can properly report CurrentSession
		m := *Map.SessionManager()
		m.CurrentSession = &s.UserSession

		// TODO: we could maintain SessionList as part of the SessionManager singleton
		sessionMutex.Lock()
		for _, session := range m.sessions {
			m.SessionList = append(m.SessionList, session.UserSession)
		}
		sessionMutex.Unlock()

		return &m
	case "PropertyCollector":
		if ref == Map.content().PropertyCollector {
			// Per-session instance of the PropertyCollector singleton.
			// Using reflection here as PropertyCollector might be wrapped with a custom type.
			obj = Map.Get(ref)
			pc := reflect.New(reflect.TypeOf(obj).Elem())
			obj = pc.Interface().(mo.Reference)
			s.Registry.setReference(obj, ref)
			return s.Put(obj)
		}
	}

	return Map.Get(ref)
}