-
-
Notifications
You must be signed in to change notification settings - Fork 928
/
session.go
364 lines (299 loc) · 10.8 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
// Copyright © 2023 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package session
import (
"context"
"database/sql/driver"
"encoding/json"
"fmt"
"net/http"
"strings"
"time"
"github.com/ory/kratos/x"
"github.com/ory/x/httpx"
"github.com/ory/x/pagination/keysetpagination"
"github.com/ory/x/stringsx"
"github.com/pkg/errors"
"github.com/gofrs/uuid"
"github.com/ory/herodot"
"github.com/ory/kratos/identity"
"github.com/ory/x/randx"
)
var ErrIdentityDisabled = herodot.ErrUnauthorized.WithError("identity is disabled").WithReason("This account was disabled.")
type lifespanProvider interface {
SessionLifespan(ctx context.Context) time.Duration
}
type refreshWindowProvider interface {
SessionRefreshMinTimeLeft(ctx context.Context) time.Duration
}
// Device corresponding to a Session
//
// swagger:model sessionDevice
type Device struct {
// Device record ID
//
// required: true
ID uuid.UUID `json:"id" faker:"-" db:"id"`
// SessionID is a helper struct field for gobuffalo.pop.
SessionID uuid.UUID `json:"-" faker:"-" db:"session_id"`
// IPAddress of the client
IPAddress *string `json:"ip_address" faker:"ptr_ipv4" db:"ip_address"`
// UserAgent of the client
UserAgent *string `json:"user_agent" faker:"-" db:"user_agent"`
// Geo Location corresponding to the IP Address
Location *string `json:"location" faker:"ptr_geo_location" db:"location"`
// Time of capture
CreatedAt time.Time `json:"-" faker:"-" db:"created_at"`
// Last updated at
UpdatedAt time.Time `json:"-" faker:"-" db:"updated_at"`
NID uuid.UUID `json:"-" faker:"-" db:"nid"`
}
func (m Device) TableName(ctx context.Context) string {
return "session_devices"
}
// A Session
//
// swagger:model session
type Session struct {
// Session ID
//
// required: true
ID uuid.UUID `json:"id" faker:"-" db:"id"`
// Active state. If false the session is no longer active.
Active bool `json:"active" db:"active"`
// The Session Expiry
//
// When this session expires at.
ExpiresAt time.Time `json:"expires_at" db:"expires_at" faker:"time_type"`
// The Session Authentication Timestamp
//
// When this session was authenticated at. If multi-factor authentication was used this
// is the time when the last factor was authenticated (e.g. the TOTP code challenge was completed).
AuthenticatedAt time.Time `json:"authenticated_at" db:"authenticated_at" faker:"time_type"`
// AuthenticationMethod Assurance Level (AAL)
//
// The authenticator assurance level can be one of "aal1", "aal2", or "aal3". A higher number means that it is harder
// for an attacker to compromise the account.
//
// Generally, "aal1" implies that one authentication factor was used while AAL2 implies that two factors (e.g.
// password + TOTP) have been used.
//
// To learn more about these levels please head over to: https://www.ory.sh/kratos/docs/concepts/credentials
AuthenticatorAssuranceLevel identity.AuthenticatorAssuranceLevel `faker:"len=4" db:"aal" json:"authenticator_assurance_level"`
// Authentication Method References (AMR)
//
// A list of authentication methods (e.g. password, oidc, ...) used to issue this session.
AMR AuthenticationMethods `db:"authentication_methods" json:"authentication_methods"`
// The Session Issuance Timestamp
//
// When this session was issued at. Usually equal or close to `authenticated_at`.
IssuedAt time.Time `json:"issued_at" db:"issued_at" faker:"time_type"`
// The Logout Token
//
// Use this token to log out a user.
LogoutToken string `json:"-" db:"logout_token"`
// required: true
Identity *identity.Identity `json:"identity" faker:"identity" db:"-" belongs_to:"identities" fk_id:"IdentityID"`
// Devices has history of all endpoints where the session was used
Devices []Device `json:"devices" faker:"-" has_many:"session_devices" fk_id:"session_id"`
// IdentityID is a helper struct field for gobuffalo.pop.
IdentityID uuid.UUID `json:"-" faker:"-" db:"identity_id"`
// CreatedAt is a helper struct field for gobuffalo.pop.
CreatedAt time.Time `json:"-" faker:"-" db:"created_at"`
// UpdatedAt is a helper struct field for gobuffalo.pop.
UpdatedAt time.Time `json:"-" faker:"-" db:"updated_at"`
// The Session Token
//
// The token of this session.
Token string `json:"-" db:"token"`
NID uuid.UUID `json:"-" faker:"-" db:"nid"`
}
func (s Session) PageToken() keysetpagination.PageToken {
return keysetpagination.StringPageToken(s.ID.String())
}
func (s Session) DefaultPageToken() keysetpagination.PageToken {
return keysetpagination.StringPageToken(uuid.Nil.String())
}
func (s Session) TableName(ctx context.Context) string {
return "sessions"
}
func (s *Session) CompletedLoginFor(method identity.CredentialsType, aal identity.AuthenticatorAssuranceLevel) {
s.AMR = append(s.AMR, AuthenticationMethod{Method: method, AAL: aal, CompletedAt: time.Now().UTC()})
}
func (s *Session) CompletedLoginForWithProvider(method identity.CredentialsType, aal identity.AuthenticatorAssuranceLevel, providerID string) {
s.AMR = append(s.AMR, AuthenticationMethod{Method: method, AAL: aal, Provider: providerID, CompletedAt: time.Now().UTC()})
}
func (s *Session) AuthenticatedVia(method identity.CredentialsType) bool {
for _, authMethod := range s.AMR {
if authMethod.Method == method {
return true
}
}
return false
}
func (s *Session) SetAuthenticatorAssuranceLevel() {
if len(s.AMR) == 0 {
// No AMR is set
s.AuthenticatorAssuranceLevel = identity.NoAuthenticatorAssuranceLevel
}
var isAAL1, isAAL2 bool
for _, amr := range s.AMR {
switch amr.AAL {
case identity.AuthenticatorAssuranceLevel1:
isAAL1 = true
case identity.AuthenticatorAssuranceLevel2:
isAAL2 = true
case "":
// Sessions before Ory Kratos 0.9 did not have the AAL
// be part of the AMR.
switch amr.Method {
case identity.CredentialsTypeRecoveryLink:
case identity.CredentialsTypeRecoveryCode:
isAAL1 = true
case identity.CredentialsTypeOIDC:
isAAL1 = true
case "v0.6_legacy_session":
isAAL1 = true
case identity.CredentialsTypePassword:
isAAL1 = true
case identity.CredentialsTypeWebAuthn:
isAAL2 = true
case identity.CredentialsTypeTOTP:
isAAL2 = true
case identity.CredentialsTypeLookup:
isAAL2 = true
}
}
}
if isAAL1 && isAAL2 {
s.AuthenticatorAssuranceLevel = identity.AuthenticatorAssuranceLevel2
} else if isAAL1 {
s.AuthenticatorAssuranceLevel = identity.AuthenticatorAssuranceLevel1
} else if len(s.AMR) > 0 {
// A fallback. If an AMR is set but we did not satisfy the above, gracefully fall back to level 1.
s.AuthenticatorAssuranceLevel = identity.AuthenticatorAssuranceLevel1
}
}
func NewActiveSession(r *http.Request, i *identity.Identity, c lifespanProvider, authenticatedAt time.Time, completedLoginFor identity.CredentialsType, completedLoginAAL identity.AuthenticatorAssuranceLevel) (*Session, error) {
s := NewInactiveSession()
s.CompletedLoginFor(completedLoginFor, completedLoginAAL)
if err := s.Activate(r, i, c, authenticatedAt); err != nil {
return nil, err
}
return s, nil
}
func NewInactiveSession() *Session {
return &Session{
ID: uuid.Nil,
Token: x.OrySessionToken + randx.MustString(32, randx.AlphaNum),
LogoutToken: x.OryLogoutToken + randx.MustString(32, randx.AlphaNum),
Active: false,
AuthenticatorAssuranceLevel: identity.NoAuthenticatorAssuranceLevel,
}
}
func (s *Session) Activate(r *http.Request, i *identity.Identity, c lifespanProvider, authenticatedAt time.Time) error {
if i != nil && !i.IsActive() {
return ErrIdentityDisabled.WithDetail("identity_id", i.ID)
}
s.Active = true
s.ExpiresAt = authenticatedAt.Add(c.SessionLifespan(r.Context()))
s.AuthenticatedAt = authenticatedAt
s.IssuedAt = authenticatedAt
s.Identity = i
s.IdentityID = i.ID
s.SetSessionDeviceInformation(r)
s.SetAuthenticatorAssuranceLevel()
return nil
}
func (s *Session) SetSessionDeviceInformation(r *http.Request) {
device := Device{
SessionID: s.ID,
IPAddress: stringsx.GetPointer(httpx.ClientIP(r)),
}
agent := r.Header["User-Agent"]
if len(agent) > 0 {
device.UserAgent = stringsx.GetPointer(strings.Join(agent, " "))
}
var clientGeoLocation []string
if r.Header.Get("Cf-Ipcity") != "" {
clientGeoLocation = append(clientGeoLocation, r.Header.Get("Cf-Ipcity"))
}
if r.Header.Get("Cf-Ipcountry") != "" {
clientGeoLocation = append(clientGeoLocation, r.Header.Get("Cf-Ipcountry"))
}
device.Location = stringsx.GetPointer(strings.Join(clientGeoLocation, ", "))
s.Devices = append(s.Devices, device)
}
func (s Session) Declassified() *Session {
s.Identity = s.Identity.CopyWithoutCredentials()
return &s
}
func (s *Session) IsActive() bool {
return s.Active && s.ExpiresAt.After(time.Now()) && (s.Identity == nil || s.Identity.IsActive())
}
func (s *Session) Refresh(ctx context.Context, c lifespanProvider) *Session {
s.ExpiresAt = time.Now().Add(c.SessionLifespan(ctx)).UTC()
return s
}
func (s *Session) MarshalJSON() ([]byte, error) {
type ss Session
out := ss(*s)
out.Active = s.IsActive()
return json.Marshal(out)
}
func (s *Session) CanBeRefreshed(ctx context.Context, c refreshWindowProvider) bool {
return s.ExpiresAt.Add(-c.SessionRefreshMinTimeLeft(ctx)).Before(time.Now())
}
// List of (Used) AuthenticationMethods
//
// A list of authenticators which were used to authenticate the session.
//
// swagger:model sessionAuthenticationMethods
type AuthenticationMethods []AuthenticationMethod
// AuthenticationMethod identifies an authentication method
//
// A singular authenticator used during authentication / login.
//
// swagger:model sessionAuthenticationMethod
type AuthenticationMethod struct {
// The method used in this authenticator.
Method identity.CredentialsType `json:"method"`
// The AAL this method introduced.
AAL identity.AuthenticatorAssuranceLevel `json:"aal"`
// When the authentication challenge was completed.
CompletedAt time.Time `json:"completed_at"`
// OIDC or SAML provider id used for authentication
Provider string `json:"provider,omitempty"`
}
// Scan implements the Scanner interface.
func (n *AuthenticationMethod) Scan(value interface{}) error {
v := fmt.Sprintf("%s", value)
if len(v) == 0 {
return nil
}
return errors.WithStack(json.Unmarshal([]byte(v), n))
}
// Value implements the driver Valuer interface.
func (n AuthenticationMethod) Value() (driver.Value, error) {
value, err := json.Marshal(n)
if err != nil {
return nil, errors.WithStack(err)
}
return string(value), nil
}
// Scan implements the Scanner interface.
func (n *AuthenticationMethods) Scan(value interface{}) error {
v := fmt.Sprintf("%s", value)
if len(v) == 0 {
return nil
}
return errors.WithStack(json.Unmarshal([]byte(v), n))
}
// Value implements the driver Valuer interface.
func (n AuthenticationMethods) Value() (driver.Value, error) {
value, err := json.Marshal(n)
if err != nil {
return nil, errors.WithStack(err)
}
return string(value), nil
}