-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathsession.go
380 lines (330 loc) · 11.4 KB
/
session.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
package lime
import (
"encoding/base64"
"encoding/json"
"errors"
"fmt"
)
// The Session envelope is used for the negotiation, authentication and establishment of the communication channel
// between the client and a server.
type Session struct {
Envelope
// State informs or changes the state of a session.
// Only the server can change the session state, but the client can request
// the state transition.
State SessionState
// EncryptionOptions represent the options provided by the server during the session negotiation.
EncryptionOptions []SessionEncryption
// Encryption represents the encryption option selected for the session.
// This property is provided by the client in the negotiation and by the
// server in the confirmation after that.
Encryption SessionEncryption
// Compression options provided by the server during the session negotiation.
CompressionOptions []SessionCompression
// The compression option selected for the session.
// This property is provided by the client in the negotiation and by the
// server in the confirmation after that.
Compression SessionCompression
// List of available authentication schemas for session authentication provided
// by the server.
SchemeOptions []AuthenticationScheme
// The authentication scheme option selected for the session.
// This property must be present if the property authentication is defined.
Scheme AuthenticationScheme
// Authentication data, related To the selected schema.
// Information like password sent by the client or round-trip data sent by the server.
Authentication Authentication
// In cases where the client receives a session with failed state,
// this property should provide more details about the problem.
Reason *Reason
}
func (s *Session) SetAuthentication(a Authentication) {
s.Authentication = a
s.Scheme = a.GetAuthenticationScheme()
}
func (s *Session) MarshalJSON() ([]byte, error) {
raw, err := s.toRawEnvelope()
if err != nil {
return nil, err
}
return json.Marshal(raw)
}
func (s *Session) UnmarshalJSON(b []byte) error {
raw := rawEnvelope{}
err := json.Unmarshal(b, &raw)
if err != nil {
return err
}
session := Session{}
err = session.populate(&raw)
if err != nil {
return err
}
*s = session
return nil
}
func (s *Session) toRawEnvelope() (*rawEnvelope, error) {
raw, err := s.Envelope.toRawEnvelope()
if err != nil {
return nil, err
}
if s.Authentication != nil {
b, err := json.Marshal(s.Authentication)
if err != nil {
return nil, err
}
a := json.RawMessage(b)
raw.Authentication = &a
if s.Scheme != "" {
raw.Scheme = &s.Scheme
}
}
if s.State != "" {
raw.State = &s.State
}
raw.EncryptionOptions = s.EncryptionOptions
if s.Encryption != "" {
raw.Encryption = &s.Encryption
}
raw.CompressionOptions = s.CompressionOptions
if s.Compression != "" {
raw.Compression = &s.Compression
}
raw.SchemeOptions = s.SchemeOptions
if s.Scheme != "" {
raw.Scheme = &s.Scheme
}
raw.Reason = s.Reason
return raw, nil
}
func (s *Session) populate(raw *rawEnvelope) error {
err := s.Envelope.populate(raw)
if err != nil {
return err
}
// Create the auth type instance and unmarshal the json to it
if raw.Authentication != nil {
if raw.Scheme == nil {
return errors.New("session scheme is required when authentication is present")
}
factory, ok := authFactories[*raw.Scheme]
if !ok {
return fmt.Errorf(`unknown authentication scheme '%v'`, raw.Scheme)
}
a := factory()
err := json.Unmarshal(*raw.Authentication, &a)
if err != nil {
return err
}
s.Authentication = a
s.Scheme = *raw.Scheme
}
if raw.State == nil {
return errors.New("session state is required")
}
s.State = *raw.State
s.EncryptionOptions = raw.EncryptionOptions
if raw.Encryption != nil {
s.Encryption = *raw.Encryption
}
s.CompressionOptions = raw.CompressionOptions
if raw.Compression != nil {
s.Compression = *raw.Compression
}
s.SchemeOptions = raw.SchemeOptions
if raw.Scheme != nil {
s.Scheme = *raw.Scheme
}
s.Reason = raw.Reason
return nil
}
// SessionState Defines the supported session states
type SessionState string
const (
// SessionStateNew indicates that the session is new and doesn't exist an established context.
// It is sent by a client node To start a session with a server.
SessionStateNew = SessionState("new")
// SessionStateNegotiating indicates that the server and the client are negotiating the session options,
// like cryptography and compression.
// The server sends To the client the options (if available) and
// the client chooses the desired options. If there's no options
// (for instance, if the connection is already encrypted or the
// transport protocol doesn't support these options), the server
// SHOULD skip the negotiation.
SessionStateNegotiating = SessionState("negotiating")
// SessionStateAuthenticating indicates that the session is being authenticated. The server sends To
// the client the available authentication schemes list and
// the client must choose one and send the specific authentication
// data. The authentication can occur in multiple round trips,
// according To the selected schema.
SessionStateAuthenticating = SessionState("authenticating")
// SessionStateEstablished indicates that the session is active, and it is possible To send and receive
// messages and commands. The server sends this state
// after the session was authenticated.
SessionStateEstablished = SessionState("established")
// SessionStateFinishing indicates that the client node is requesting to the server to finish the session.
SessionStateFinishing = SessionState("finishing")
// SessionStateFinished indicates that the session was gracefully finished by the server.
SessionStateFinished = SessionState("finished")
// SessionStateFailed indicates that a problem occurred while the session was established, under
// negotiation or authentication, and it was closed by the server.
// In this case, the property reason MUST be present to provide
// more details about the problem.
SessionStateFailed = SessionState("failed")
)
func (s SessionState) Validate() error {
switch s {
case SessionStateNew, SessionStateNegotiating, SessionStateAuthenticating, SessionStateEstablished, SessionStateFinishing, SessionStateFinished, SessionStateFailed:
return nil
}
return fmt.Errorf("invalid session state '%v'", s)
}
func (s SessionState) Step() int {
switch s {
case SessionStateNew:
return 0
case SessionStateNegotiating:
return 1
case SessionStateAuthenticating:
return 2
case SessionStateEstablished:
return 3
case SessionStateFinishing:
return 4
case SessionStateFinished:
return 5
case SessionStateFailed:
return 6
}
return -1
}
func (s SessionState) MarshalText() ([]byte, error) {
err := s.Validate()
if err != nil {
return []byte{}, err
}
return []byte(s), nil
}
func (s *SessionState) UnmarshalText(text []byte) error {
state := SessionState(text)
err := state.Validate()
if err != nil {
return err
}
*s = state
return nil
}
// SessionEncryption Defines the valid session encryption values.
type SessionEncryption string
const (
// SessionEncryptionNone The session is not encrypted.
SessionEncryptionNone = SessionEncryption("none")
// SessionEncryptionTLS The session is encrypted by TLS (Transport Layer Security).
SessionEncryptionTLS = SessionEncryption("tls")
)
// SessionCompression Defines the valid session compression values.
type SessionCompression string
const (
// SessionCompressionNone The session is not compressed.
SessionCompressionNone = SessionCompression("none")
// SessionCompressionGzip The session is using the GZip algorithm for compression.
SessionCompressionGzip = SessionCompression("gzip")
)
// AuthenticationScheme Defines the valid authentication schemes values.
type AuthenticationScheme string
const (
// AuthenticationSchemeGuest The server doesn't require a client credential, and provides a temporary
// identity to the node. Some restriction may apply To guest sessions, like
// the inability of sending some commands or other nodes may want To block
// messages originated by guest identities.
AuthenticationSchemeGuest = AuthenticationScheme("guest")
// AuthenticationSchemePlain Username and password authentication.
AuthenticationSchemePlain = AuthenticationScheme("plain")
// AuthenticationSchemeKey Key authentication.
AuthenticationSchemeKey = AuthenticationScheme("key")
// AuthenticationSchemeTransport Transport layer authentication.
AuthenticationSchemeTransport = AuthenticationScheme("transport")
// AuthenticationSchemeExternal Third-party authentication.
AuthenticationSchemeExternal = AuthenticationScheme("external")
)
var authFactories = map[AuthenticationScheme]func() Authentication{
AuthenticationSchemeGuest: func() Authentication {
return &GuestAuthentication{}
},
AuthenticationSchemePlain: func() Authentication {
return &PlainAuthentication{}
},
AuthenticationSchemeKey: func() Authentication {
return &KeyAuthentication{}
},
AuthenticationSchemeTransport: func() Authentication {
return &TransportAuthentication{}
},
AuthenticationSchemeExternal: func() Authentication {
return &ExternalAuthentication{}
},
}
// Authentication defines a session authentications scheme container
type Authentication interface {
GetAuthenticationScheme() AuthenticationScheme
}
// GuestAuthentication defines a guest authentication scheme.
type GuestAuthentication struct {
}
func (g *GuestAuthentication) GetAuthenticationScheme() AuthenticationScheme {
return AuthenticationSchemeGuest
}
// PlainAuthentication defines a plain authentication scheme, that uses a password for authentication.
// Should be used only with encrypted sessions.
type PlainAuthentication struct {
// Password is the base64 representation of the password.
Password string `json:"password"`
}
func (a *PlainAuthentication) GetAuthenticationScheme() AuthenticationScheme {
return AuthenticationSchemePlain
}
func (a *PlainAuthentication) SetPasswordAsBase64(password string) {
a.Password = base64.StdEncoding.EncodeToString([]byte(password))
}
func (a *PlainAuthentication) GetPasswordFromBase64() (string, error) {
str, err := base64.StdEncoding.DecodeString(a.Password)
if err != nil {
return "", err
}
return string(str), nil
}
// KeyAuthentication defines a plain authentication scheme, that uses a key for authentication.
// Should be used only with encrypted sessions.
type KeyAuthentication struct {
// Base64 representation of the key
Key string `json:"key"`
}
func (a *KeyAuthentication) GetAuthenticationScheme() AuthenticationScheme {
return AuthenticationSchemeKey
}
func (a *KeyAuthentication) SetKeyAsBase64(key string) {
a.Key = base64.StdEncoding.EncodeToString([]byte(key))
}
func (a *KeyAuthentication) GetKeyFromBase64() (string, error) {
str, err := base64.StdEncoding.DecodeString(a.Key)
if err != nil {
return "", err
}
return string(str), nil
}
// TransportAuthentication defines a transport layer authentication scheme.
type TransportAuthentication struct {
}
func (a *TransportAuthentication) GetAuthenticationScheme() AuthenticationScheme {
return AuthenticationSchemeTransport
}
// ExternalAuthentication defines an external authentication scheme, that uses third-party validation.
type ExternalAuthentication struct {
// The authentication token on base64 representation.
Token string `json:"token"`
// The trusted token issuer.
Issuer string `json:"issuer"`
}
func (a *ExternalAuthentication) GetAuthenticationScheme() AuthenticationScheme {
return AuthenticationSchemeExternal
}