Module: Sessions::Adapters::Warden

Defined in:
lib/sessions/adapters/warden.rb

Overview

The Devise/Warden adapter — four class-level Warden hooks, registered from the engine ONLY when ‘::Warden::Manager` is already loaded (Bundler.require precedes initializers, so the check is decisive; the gem never `require`s warden itself and stays inert in non-Warden apps).

The revocation mechanism generalizes devise-security’s proven ‘session_limitable` (a complete 55-line template whose only structural flaw is one-token-per-user): the token moves from a users-table column to a sessions-table ROW, turning “exactly one session” into “N devices, each individually revocable” (→ docs/research/04-devise-warden.md §5).

login  — mint a random token, store structured tracking state in the
         per-scope warden session (it survives Warden's :renew SID
         rotation and is deleted by Warden itself on logout; we
         never key on the Rack SID), persist only the SHA-256
         digest on the row.
fetch  — per-request liveness check: row exists + digest matches
         (constant-time) + row is live → throttled touch; row ended
         for an explicit reason → the proven session_limitable kick:
         clear, logout, throw. Missing/mismatched tracking fails open
         unless a legacy v0.1.x event tombstone proves a pre-lifecycle
         remote revocation.
failure — record the failed attempt with the typed identity.
logout — mark the row ended, labeled as a logout.

Constant Summary collapse

SESSION_KEY =

Key inside ‘warden.session(scope)` holding the sessions gem tracking state. v0.2 writes a small Hash (`id`, `token`, `mode`) instead of the old `[row_id, raw_token]` tuple so a nil token can never accidentally read like an auth credential. The parser still accepts arrays because production users may carry v0.1.x cookies during deploy.

"sessions"
PENDING_LOGIN_KEY =

Rememberable can restore a user on background/native JSON requests before the browser/WebView has actually navigated. Defer the row until a document request can name the user-visible device.

"sessions.pending_login"
SKIP_SESSION_KEY =

Sticky per-scope flag: a login recorded with ‘sessions_skip: true` must not be kicked by the fetch validation later (session_limitable’s third skip layer).

"sessions.skip"
SKIP_ENV_KEY =

Request-wide skip: ‘request.env = true`.

"sessions.skip"
THROW_MESSAGE =

The ‘throw :warden` message on revoked sessions — Devise’s failure app surfaces it like :timeout/:session_limited. The gem SHIPS the ‘devise.failure.session_revoked` copy (en + es, config/locales/); hosts override that key for custom wording.

:session_revoked

Class Method Summary collapse

Class Method Details

.activate_pending_login(record, warden, scope, pending_login) ⇒ Object



284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
# File 'lib/sessions/adapters/warden.rb', line 284

def (record, warden, scope, )
  Sessions.safely("warden.pending_login") do
    next unless row_accepts?(record)
    next unless document_request?(warden.request)

    if (row = pending_existing_row(record, warden, scope, ))
      attach_existing_row(row, warden, scope)
      warden.session(scope).delete(PENDING_LOGIN_KEY)
      next row
    end

    row = create_row_for(record, warden, scope, attributes: ())
    warden.session(scope).delete(PENDING_LOGIN_KEY)
    row
  end
end

.adopt_preexisting_session(record, warden, scope) ⇒ Object

A session that predates the gem (no token in the warden session): adopt it so existing logged-in users appear on their devices page right after deploy — a row is minted with ‘auth_method: “unknown”` and NO login event (adoption isn’t a login; the trail stays honest). Never kicks anyone: adoption failures degrade to “untracked”.



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
# File 'lib/sessions/adapters/warden.rb', line 258

def adopt_preexisting_session(record, warden, scope)
  Sessions.safely("warden.adopt") do
    next unless row_accepts?(record)
    next unless document_request?(warden.request)

    # IDEMPOTENT, because a client that can't persist cookies re-enters
    # adoption on EVERY request: the SESSION_KEY we write rides a
    # Set-Cookie the client drops, so the next request adopts again.
    #
    # Adoption is intentionally coarse: it is a low-fidelity marker for
    # "this owner already had an authenticated session when the gem
    # arrived", not a real login. One owner+scope marker is enough. Do
    # not key it on UA (Hotwire Native devices legitimately use WebView
    # and native-client UAs) or time (cookie-dropping clients would mint
    # one per day forever). When the adoption_key column is present, the
    # unique index makes the first concurrent burst atomic.
    adoption_key = adoption_key_for(record, scope)
    if (row = adopted_row(record, scope, adoption_key: adoption_key))
      Sessions.safely("warden.adopt.touch") { row.touch_last_seen!(warden.request) }
      next
    end

    create_adopted_row(record, warden, scope, adoption_key: adoption_key)
  end
end

.adopted_row(record, scope, adoption_key:) ⇒ Object



438
439
440
441
442
443
444
445
446
447
448
# File 'lib/sessions/adapters/warden.rb', line 438

def adopted_row(record, scope, adoption_key:)
  model = Sessions.session_model
  rows = model.live.where(user: record)
  rows = rows.where(scope: scope.to_s) if model.column_names.include?("scope")

  row = model.live.find_by(adoption_key: adoption_key) if adoption_key_column?(model) && adoption_key.present?
  row = nil unless adopted_row?(row)
  row ||= rows.order(created_at: :desc).detect { |candidate| adopted_row?(candidate) }

  claim_adoption_key(row, adoption_key)
end

.adopted_row?(row) ⇒ Boolean

Returns:

  • (Boolean)


450
451
452
# File 'lib/sessions/adapters/warden.rb', line 450

def adopted_row?(row)
  row && row.try(:auth_detail).to_h["adopted"]
end

.adoption_key_column?(model = Sessions.session_model) ⇒ Boolean

Returns:

  • (Boolean)


479
480
481
# File 'lib/sessions/adapters/warden.rb', line 479

def adoption_key_column?(model = Sessions.session_model)
  model.column_names.include?("adoption_key")
end

.adoption_key_for(record, scope) ⇒ Object



466
467
468
469
470
471
472
473
474
475
476
477
# File 'lib/sessions/adapters/warden.rb', line 466

def adoption_key_for(record, scope)
  owner_id = record.respond_to?(:to_key) ? Array(record.to_key).join("/") : record.try(:id)
  return if owner_id.blank?

  owner_type = if record.class.respond_to?(:polymorphic_name)
                 record.class.polymorphic_name
               else
                 record.class.name
               end

  "adopt:#{Sessions.token_digest([owner_type, owner_id, scope.to_s].join("\0"))}"
end

.attach_existing_row(row, warden, scope) ⇒ Object



348
349
350
351
352
# File 'lib/sessions/adapters/warden.rb', line 348

def attach_existing_row(row, warden, scope)
  warden.session(scope)[SESSION_KEY] = tracking_state(row, mode: "hint")
  Sessions.safely("warden.remembered_existing.touch") { row.touch_last_seen!(warden.request) }
  row
end

.claim_adoption_key(row, adoption_key) ⇒ Object



454
455
456
457
458
459
460
461
462
463
464
# File 'lib/sessions/adapters/warden.rb', line 454

def claim_adoption_key(row, adoption_key)
  return row unless row
  return row unless adoption_key_column?(row.class)
  return row if adoption_key.blank? || row.try(:adoption_key).present?

  row.update_columns(adoption_key: adoption_key)
  row.adoption_key = adoption_key
  row
rescue ActiveRecord::RecordNotUnique
  row.class.find_by(adoption_key: adoption_key) || row
end

.clear_tracking_key(warden, scope) ⇒ Object



483
484
485
486
487
# File 'lib/sessions/adapters/warden.rb', line 483

def clear_tracking_key(warden, scope)
  warden.session(scope).delete(SESSION_KEY)
rescue StandardError
  nil
end

.create_adopted_row(record, warden, scope, adoption_key:) ⇒ Object



427
428
429
430
431
432
433
434
435
436
# File 'lib/sessions/adapters/warden.rb', line 427

def create_adopted_row(record, warden, scope, adoption_key:)
  attributes = { auth_detail: { "adopted" => true } }
  attributes[:adoption_key] = adoption_key if adoption_key_column?

  create_row_for(record, warden, scope, suppress_login_event: true, skip_supersede: true, attributes: attributes)
rescue ActiveRecord::RecordNotUnique
  adopted_row(record, scope, adoption_key: adoption_key)&.tap do |row|
    Sessions.safely("warden.adopt.touch") { row.touch_last_seen!(warden.request) }
  end
end

.create_row_for(record, warden, scope, suppress_login_event: false, skip_supersede: false, attributes: {}) ⇒ Object



135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
# File 'lib/sessions/adapters/warden.rb', line 135

def create_row_for(record, warden, scope, suppress_login_event: false, skip_supersede: false, attributes: {})
  token = Sessions.generate_token
  request = warden.request
  model = Sessions.session_model

  row = model.new(
    user: record,
    scope: scope.to_s,
    ip_address: Sessions::IpAddress.resolve(request),
    user_agent: request.user_agent,
    token_digest: Sessions.token_digest(token)
  ).tap do |session|
    attributes.each do |column, value|
      session[column] = value if model.column_names.include?(column.to_s)
    end
  end
  row. = 
  row.sessions_skip_supersede = skip_supersede
  Sessions.with_request(request) { row.save! }

  warden.session(scope)[SESSION_KEY] = tracking_state(row, token: token, mode: "credential")
  row
end

.deferred_login_request?(request, auth) ⇒ Boolean

Returns:

  • (Boolean)


301
302
303
# File 'lib/sessions/adapters/warden.rb', line 301

def (request, auth)
  remembered_login?(auth) && !document_request?(request)
end

.device_id_from_request(request) ⇒ Object



381
382
383
384
385
386
387
# File 'lib/sessions/adapters/warden.rb', line 381

def device_id_from_request(request)
  return unless request.respond_to?(:cookie_jar)

  request.cookie_jar.signed[Sessions::DEVICE_COOKIE].presence
rescue StandardError
  nil
end

.document_request?(request) ⇒ Boolean

Returns:

  • (Boolean)


389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
# File 'lib/sessions/adapters/warden.rb', line 389

def document_request?(request)
  return true unless request
  return false if non_document_path?(request)

  accept = request_header(request, "HTTP_ACCEPT").to_s
  return true if accept.empty? || accept == "*/*"
  return true if accept.match?(%r{\btext/html\b|\bapplication/xhtml\+xml\b|\btext/vnd\.turbo-stream\.html\b})
  return false if accept.match?(%r{\b(?:application|text)/(?:[\w.+-]+\+)?json\b})
  return false if request_header(request, "HTTP_X_REQUESTED_WITH").to_s.casecmp("XMLHttpRequest").zero?

  if request.respond_to?(:format)
    format = request.format
    return true if format.respond_to?(:html?) && format.html?
    return false if format.respond_to?(:json?) && format.json?
  end

  true
rescue StandardError
  true
end

.end_row_for_auth_teardown(row, reason:, context:) ⇒ Object



640
641
642
643
644
645
646
# File 'lib/sessions/adapters/warden.rb', line 640

def end_row_for_auth_teardown(row, reason:, context:)
  row.end!(reason: reason)
  true
rescue StandardError => e
  Sessions.warn("#{context} failed open: #{e.class}: #{e.message}")
  false
end

.existing_row_session?(row, record, scope, request) ⇒ Boolean

Returns:

  • (Boolean)


354
355
356
357
358
359
360
361
362
363
364
365
366
# File 'lib/sessions/adapters/warden.rb', line 354

def existing_row_session?(row, record, scope, request)
  return false unless row

  device_id = device_id_from_request(request)
  return false if device_id.blank?
  return false unless row.try(:device_id) == device_id
  return false unless row.user == record
  return false if row.respond_to?(:scope) && row.scope.present? && row.scope != scope.to_s

  true
rescue StandardError
  false
end

.install!Object



58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/sessions/adapters/warden.rb', line 58

def install!
  return if @installed

  @installed = true

  ::Warden::Manager.after_set_user(except: :fetch) do |record, warden, opts|
    Sessions::Adapters::Warden.(record, warden, opts)
  end

  ::Warden::Manager.after_set_user(only: :fetch) do |record, warden, opts|
    Sessions::Adapters::Warden.validate_session(record, warden, opts)
  end

  ::Warden::Manager.before_failure do |env, opts|
    Sessions::Adapters::Warden.record_failure(env, opts)
  end

  ::Warden::Manager.before_logout do |record, warden, opts|
    Sessions::Adapters::Warden.record_logout(record, warden, opts)
  end
end

.installed?Boolean

Test seam.

Returns:

  • (Boolean)


81
82
83
# File 'lib/sessions/adapters/warden.rb', line 81

def installed?
  !!@installed
end

.kick!(warden, scope) ⇒ Object

SCOPE-PRECISE teardown: only this scope’s warden entries go (the serialized user key and our token stash) — an admin scope riding the same rack session, and unrelated host session data (carts, locale, return-to paths), survive a user-scope kick. Deleting the keys BEFORE logout matters: our before_logout hook then finds no token and records nothing (a kick is not a logout — the lifecycle reason/event were already written by the explicit ending).



537
538
539
540
541
542
# File 'lib/sessions/adapters/warden.rb', line 537

def kick!(warden, scope)
  warden.raw_session.delete("warden.user.#{scope}.key")
  warden.raw_session.delete("warden.user.#{scope}.session")
  warden.logout(scope)
  throw :warden, scope: scope, message: THROW_MESSAGE
end

.legacy_explicitly_ended_session?(id) ⇒ Boolean

Returns:

  • (Boolean)


519
520
521
522
523
524
525
526
527
528
# File 'lib/sessions/adapters/warden.rb', line 519

def legacy_explicitly_ended_session?(id)
  return false if id.blank?

  events = Sessions::Event.where(session_id: id)
  events.expirations.exists? ||
    events.revocations.where.not(revoked_reason: "superseded").exists?
rescue StandardError => e
  Sessions.warn("warden.fetch legacy end-event lookup failed open: #{e.class}: #{e.message}")
  false
end

.live_replacement_for(row, record, scope, request) ⇒ Object



368
369
370
371
372
373
374
375
376
377
378
379
# File 'lib/sessions/adapters/warden.rb', line 368

def live_replacement_for(row, record, scope, request)
  device_id = row&.try(:device_id).presence || device_id_from_request(request)
  return if device_id.blank?

  model = Sessions.session_model
  rows = model.live.where(user: record, device_id: device_id)
  rows = rows.where(scope: scope.to_s) if model.column_names.include?("scope")
  rows = rows.where.not(id: row.id) if row
  rows.order(created_at: :desc).first
rescue StandardError
  nil
end

.login_auth_attributes(auth) ⇒ Object



316
317
318
319
320
321
322
# File 'lib/sessions/adapters/warden.rb', line 316

def (auth)
  {
    auth_method: auth[:method],
    auth_provider: auth[:provider],
    auth_detail: auth[:detail].presence
  }.compact
end

.non_document_path?(request) ⇒ Boolean

Returns:

  • (Boolean)


410
411
412
413
414
415
416
417
# File 'lib/sessions/adapters/warden.rb', line 410

def non_document_path?(request)
  path = if request.respond_to?(:path)
           request.path
         elsif request.respond_to?(:path_info)
           request.path_info
         end
  File.extname(path.to_s).delete(".").casecmp("json").zero?
end

.parse_tracking_state(value) ⇒ Object



498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
# File 'lib/sessions/adapters/warden.rb', line 498

def parse_tracking_state(value)
  case value
  when Hash
    id = value["id"] || value[:id]
    token = value["token"] || value[:token]
    mode = (value["mode"] || value[:mode]).presence
  when Array
    id, token = value
    mode = token.present? ? "credential" : "hint"
  else
    return nil
  end

  return nil if id.blank?

  mode = token.present? ? "credential" : (mode || "hint")
  { id: id, token: token, mode: mode }
rescue StandardError
  nil
end

.pending_existing_row(record, warden, scope, pending_login) ⇒ Object



330
331
332
333
# File 'lib/sessions/adapters/warden.rb', line 330

def pending_existing_row(record, warden, scope, )
  auth = { detail: .to_h["auth_detail"] || {} }
  remembered_existing_row(record, warden, scope, auth)
end

.pending_login_attributes(attributes) ⇒ Object



324
325
326
327
328
# File 'lib/sessions/adapters/warden.rb', line 324

def (attributes)
  attributes.to_h.slice("auth_method", "auth_provider", "auth_detail")
rescue StandardError
  {}
end

.record_failure(env, opts) ⇒ Object

— Hook 3: failed logins ————————————————



546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
# File 'lib/sessions/adapters/warden.rb', line 546

def record_failure(env, opts)
  Sessions.safely("warden.failure") do
    next unless Sessions.config.track_failed_logins
    next if env[SKIP_ENV_KEY]

    request = ActionDispatch::Request.new(env)
    # `before_failure` fires for EVERY warden failure, including plain
    # unauthenticated page-hits and timeouts. A real credential
    # failure is a POST carrying the scope's credentials hash
    # (→ research/04 §3). The password key is never read.
    next unless request.post?

    # Devise passes scope: explicitly in auth_options; a bare
    # `warden.authenticate!` throws opts WITHOUT it — fall back to the
    # stack's default scope, like Warden itself does.
    scope = opts[:scope] || warden_default_scope(env)
    credentials = request.params[scope.to_s]
    next unless credentials.is_a?(Hash)

    # `email_address` included: it's the omakase-era key, and Devise
    # apps configure `authentication_keys = [:email_address]` too.
    identity = credentials.values_at("email", "email_address", "login", "username", "phone").compact.first

    Sessions::Event.record_failure(
      request,
      scope: scope,
      identity: identity,
      # Devise's message symbol, verbatim — under paranoid mode this
      # stays :invalid; we never infer (or leak) account existence.
      reason: opts[:message],
      metadata: { attempted_path: opts[:attempted_path] }.compact
    )
  end
end

.record_login(record, warden, opts) ⇒ Object

— Hook 1: any fresh login (form, remember-me, OmniAuth, sign-up auto-login, post-password-reset) —————————————-



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
# File 'lib/sessions/adapters/warden.rb', line 92

def (record, warden, opts)
  Sessions.safely("warden.login") do
    scope = opts[:scope]
    # Guard set lifted from Devise's own hooks. The `store: false`
    # check is CRITICAL: token/HTTP-Basic strategies fire this hook on
    # EVERY request with store: false — without it we'd mint a session
    # row per API call.
    next unless warden.authenticated?(scope)
    next if opts[:store] == false
    next if warden.request.env[SKIP_ENV_KEY]
    next if record.respond_to?(:sessions_skip?) && record.sessions_skip?
    # Reauthentication (sudo-style confirms) re-runs sign_in
    # MID-SESSION — devise-passkeys' `reauthenticate` calls
    # `sign_in(..., event: :passkey_reauthentication)` (see its
    # controllers/reauthentication_controller_concern.rb), which fires
    # after_set_user like any login. That's the same person proving
    # presence on an already-tracked session, not a new device:
    # minting a row here would orphan the live one mid-request.
    next if opts[:event].to_s.match?(/reauth/i)

    if opts[:sessions_skip]
      warden.session(scope)[SKIP_SESSION_KEY] = true
      next
    end

    next unless row_accepts?(record)

    auth = Sessions::Classifier.classify(warden.request)
    if (warden.request, auth)
      (warden, scope, auth)
      next
    end

    if (row = remembered_existing_row(record, warden, scope, auth))
      attach_existing_row(row, warden, scope)
      next
    end

    warden.session(scope).delete(PENDING_LOGIN_KEY)
    create_row_for(record, warden, scope)
  end
end

.record_logout(record, warden, opts) ⇒ Object

Fires once per scope (including forced logouts: timeout, lockout, our own revocation kick). If the row is already ended, there’s nothing to do; lifecycle state is idempotent.

CRITICAL: read the RAW session here, never ‘warden.session(scope)`. Warden’s logout deletes ‘@users` BEFORE running before_logout callbacks (proxy.rb#logout), so Proxy#session’s authenticated? check would re-deserialize the user → re-fire after_set_user → and when the logout came from a hook that logs out and throws (Devise’s activatable on unconfirmed/locked accounts, timeoutable) that loops: activatable → logout → us → re-auth → activatable → … SystemStackError.



594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
# File 'lib/sessions/adapters/warden.rb', line 594

def record_logout(record, warden, opts)
  scope = opts[:scope]
  tracking = parse_tracking_state(warden.raw_session["warden.user.#{scope}.session"]&.dig(SESSION_KEY))
  return unless tracking

  row = Sessions.session_model.find_by(id: tracking[:id])
  return unless row
  return unless row.live?

  token_backed = tracking[:mode] == "credential" && row.sessions_token_matches?(tracking[:token])
  tokenless_known_device = tracking[:mode] == "hint" &&
                           existing_row_session?(row, record, scope, warden.request)
  return unless token_backed || tokenless_known_device

  # Warden 1.2.9 runs before_logout callbacks before deleting the
  # serialized session keys (proxy.rb#logout). Raising here aborts the
  # auth teardown, so an audit/lifecycle persistence failure cannot log
  # the user out while leaving the row live.
  # Source: https://github.com/wardencommunity/warden/blob/v1.2.9/lib/warden/proxy.rb#L266-L279
  row.end!(reason: :logout)
rescue StandardError => e
  Sessions.warn("warden.logout aborted auth teardown: #{e.class}: #{e.message}")
  raise
end

.remembered_existing_row(record, warden, scope, auth) ⇒ Object



335
336
337
338
339
340
341
342
343
344
345
346
# File 'lib/sessions/adapters/warden.rb', line 335

def remembered_existing_row(record, warden, scope, auth)
  return unless remembered_login?(auth)

  device_id = device_id_from_request(warden.request)
  return if device_id.blank?

  rows = Sessions.session_model.live.where(user: record, device_id: device_id)
  rows = rows.where(scope: scope.to_s) if Sessions.session_model.column_names.include?("scope")
  rows.order(created_at: :desc).first
rescue StandardError
  nil
end

.remembered_login?(auth) ⇒ Boolean

Returns:

  • (Boolean)


305
306
307
308
309
310
# File 'lib/sessions/adapters/warden.rb', line 305

def remembered_login?(auth)
  detail = auth[:detail].to_h
  detail["remembered"] || detail[:remembered]
rescue StandardError
  false
end

.request_header(request, key) ⇒ Object



419
420
421
422
423
424
425
# File 'lib/sessions/adapters/warden.rb', line 419

def request_header(request, key)
  if request.respond_to?(:get_header)
    request.get_header(key)
  elsif request.respond_to?(:env)
    request.env[key]
  end
end

.reset_installation!Object



85
86
87
# File 'lib/sessions/adapters/warden.rb', line 85

def reset_installation!
  @installed = false
end

.row_accepts?(record) ⇒ Boolean

Multi-scope safety: with a plain (non-polymorphic) ‘user` association, rows can only hold the matching class — a second Devise scope on another model stays silently untracked (re-run the install generator with –polymorphic to track every scope).

Returns:

  • (Boolean)


630
631
632
633
634
635
636
637
638
# File 'lib/sessions/adapters/warden.rb', line 630

def row_accepts?(record)
  reflection = Sessions.session_model.reflect_on_association(:user)
  return false unless reflection
  return true if reflection.polymorphic?

  record.is_a?(reflection.klass)
rescue StandardError
  false
end

.stash_pending_login(warden, scope, auth) ⇒ Object



312
313
314
# File 'lib/sessions/adapters/warden.rb', line 312

def (warden, scope, auth)
  warden.session(scope)[PENDING_LOGIN_KEY] = (auth).transform_keys(&:to_s)
end

.tracking_state(row, mode:, token: nil) ⇒ Object



489
490
491
492
493
494
495
496
# File 'lib/sessions/adapters/warden.rb', line 489

def tracking_state(row, mode:, token: nil)
  {
    "v" => 2,
    "id" => row.id,
    "token" => token,
    "mode" => mode
  }
end

.validate_session(record, warden, opts) ⇒ Object

— Hook 2: per-request resume — validate, expire, touch —————



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
# File 'lib/sessions/adapters/warden.rb', line 161

def validate_session(record, warden, opts)
  scope = opts[:scope]
  return if opts[:store] == false
  return if warden.request.env[SKIP_ENV_KEY]
  return if record.respond_to?(:sessions_skip?) && record.sessions_skip?

  data = Sessions.safely("warden.fetch") do
    session_data = warden.session(scope)
    next :skip if session_data[SKIP_SESSION_KEY]

    {
      login: session_data[SESSION_KEY],
      pending_login: session_data[PENDING_LOGIN_KEY]
    }
  end
  return if data == :skip

  tracking = parse_tracking_state(data && data[:login])
  if tracking.nil?
    if data && data[:pending_login]
      (record, warden, scope, data[:pending_login])
    else
      adopt_preexisting_session(record, warden, scope)
    end
    return
  end

  # The lookup is NOT wrapped in `safely`: an ERRORED lookup and a
  # MISSING row must be distinguishable from a raised lookup, but a
  # missing/mismatched tracking row is still not automatically auth
  # state. In v0.2, only a matching row whose own ended_reason is
  # explicit may kick. The event lookup below is legacy-only for v0.1.x
  # cookies whose rows were already destroyed before lifecycle columns
  # existed.
  # A raised lookup — the sessions table unreachable, a timeout, a
  # migration mid-deploy — means the TRACKING layer is down, and
  # tracking must never break authentication: fail OPEN, let the request
  # through untracked, try again next request.
  begin
    found = Sessions.session_model.find_by(id: tracking[:id])
    if tracking[:mode] == "hint"
      # v0.1.3 intentionally reattached remember-me restores to an
      # existing device row without writing another login event, storing
      # [row_id, nil] in Warden. That is fine as a tracking hint, but it
      # must never become an auth/liveness check. Touch when the signed
      # browser-continuity cookie still agrees; otherwise clear only the
      # gem's tracking key and let Devise/Rails keep owning auth.
      # Source: https://github.com/rameerez/sessions/blob/v0.1.3/CHANGELOG.md
      if existing_row_session?(found, record, scope, warden.request) && found.live?
        Sessions.safely("warden.remembered_existing.touch") { found.touch_last_seen!(warden.request) }
      elsif (replacement = live_replacement_for(found, record, scope, warden.request))
        attach_existing_row(replacement, warden, scope)
      else
        clear_tracking_key(warden, scope)
      end
      return
    end

    row = found if found&.sessions_token_matches?(tracking[:token])
  rescue StandardError => e
    Sessions.warn("warden.fetch failed open: #{e.class}: #{e.message}")
    return
  end

  if row.nil?
    if legacy_explicitly_ended_session?(tracking[:id])
      # Explicit remote revocation/expiry is the one intentional place
      # where a legacy v0.1.x destroyed row may still end a Devise
      # session. v0.2 rows should be present and ended in place.
      kick!(warden, scope)
    else
      clear_tracking_key(warden, scope)
    end
  elsif row.ended?
    if row.sessions_kicks_on_resume?
      kick!(warden, scope)
    elsif (replacement = live_replacement_for(row, record, scope, warden.request))
      attach_existing_row(replacement, warden, scope)
    else
      clear_tracking_key(warden, scope)
    end
  elsif Sessions.safely("warden.expired?") { row.sessions_expired? }
    # Expiry is gem-initiated, so it must be durable before we touch
    # Warden auth state. If the lifecycle write rolls back, fail open:
    # the user stays authenticated and the next request can retry the
    # expiry instead of leaving an orphan `.live` row.
    kick!(warden, scope) if end_row_for_auth_teardown(row, reason: :expired, context: "warden.expire")
  else
    Sessions.safely("warden.touch") { row.touch_last_seen!(warden.request) }
  end
end

.warden_default_scope(env) ⇒ Object



619
620
621
622
623
624
# File 'lib/sessions/adapters/warden.rb', line 619

def warden_default_scope(env)
  warden = env["warden"]
  warden.respond_to?(:config) ? warden.config.default_scope : nil
rescue StandardError
  nil
end