Skip to content

Fix DST-blind lifespan ceiling wiping all auth tokens - #537

Open
tmfrnz wants to merge 5 commits into
sg-devfrom
sg-dev-fix-dta-clean-old-tokens
Open

tmfrnz wants to merge 5 commits into
sg-devfrom
sg-dev-fix-dta-clean-old-tokens

Conversation

@tmfrnz

@tmfrnz tmfrnz commented Oct 20, 2026 •

Copy link
Copy Markdown
Member

Problem

A third sign-in (with max_number_of_devices = 2) wipes the user's entire tokens hash instead of evicting the oldest token. The response then carries no auth headers, the client saves nothing, and the user cannot sign in at all.

Reported on UAT (Edinburgh), reproduced locally: the existing spec prunes rows when max_number_of_devices is exceeded fails on sg-dev today, though it passed when #513 was merged - the failure only appears while “now + 2 weeks” crosses a DST boundary, so roughly 11-25 Oct and again before BST starts in March.

Cause

In devise_token_auth 1.2.6, User#clean_old_tokens computes the ceiling for its "token lifespan was reduced" filter with flat integer arithmetic:

max_lifespan_expiry = Time.now.to_i + DeviseTokenAuth.token_lifespan.to_i

TokenFactory.expiry computes expiries calendar-aware:

(Time.zone.now + lifespan).to_i

With config.time_zone = "Edinburgh" and token_lifespan = 2.weeks, two weeks ahead currently crosses the end of BST. The two calculations then differ by exactly 3600, confirmed on both local and UAT:

(Time.zone.now + lifespan).to_i - (Time.now.to_i + lifespan.to_i)  # => 3600

Every live token's expiry sits an hour above the ceiling, tokens_to_keep comes out empty, self.tokens = {}, and the sort-and-shift below operates on nothing. The newly minted token goes with the rest.

Only bites once the token count exceeds max_number_of_devices, since the gem returns early otherwise - hence the third sign-in. Not caused by #513; that branch made it visible (reconcile_token_activities logs a DELETE ... AND 1=1), where previously it would have silently signed everyone out. Self-resolves on 26 Oct and returns around 15 Mar, which is not a reason to leave it.

Suggested fix

Override clean_old_tokens in User, changing only the ceiling line to match how expiries are computed. The sort-and-shift is copied verbatim from the gem. Needs revisiting on any devise_token_auth upgrade.

Alternatives considered

  • config.time_zone = "UTC". Removes the category rather than one symptom, and the serializers emit ISO 8601 with offset (in_time_zone.iso8601) with no server-side strftime anywhere, so nothing user-facing renders a local time. But clock.rb passes tz: Rails.application.config.time_zone to all four Clockwork schedules, so the jobs would shift by an hour during BST unless the tz values are pinned separately. Out of scope here; worth its own issue.
  • Shorter token_lifespan. Not viable at two weeks, and the hazard would return at any duration spanning a transition.

Not fixed here

  • DueDate scopes use Date.today, which reads the system clock rather than Time.zone, so they already ignore config.time_zone. Pre-existing and unrelated.
  • Not yet checked whether this is reported upstream.

Testing

Existing spec prunes rows when max_number_of_devices is exceeded now passes.

Added a spec asserting two tokens survive a third sign-in, with the zone and date pinned (Time.use_zone("Edinburgh") + travel_to 2026-10-20) so the DST window is part of the test rather than the environment. Without that it only fails against the unfixed gem while the real clock happens to be inside a transition window, and not at all on the Auckland-configured deployments.

Unrelated: CI runner pin

Also pins both workflows to ubuntu-24.04. ubuntu-latest moved to 26.04, which only builds the latest patch of each Ruby series, so .ruby-version at 3.3.7 fails setup and neither rspec nor standardrb runs. Bumping .ruby-version to 3.3.12 is the real fix, but Gemfile has ruby file: ".ruby-version", so it changes the deployed runtime too and wants its own change.

@tmfrnz
tmfrnz requested a review from parndt October 20, 2026 09:06
@parndt

parndt commented Oct 20, 2026

Copy link
Copy Markdown
Collaborator

Looks like we need to upgrade ruby to at least 3.3.12 for ubuntu-latest, I'll open a PR

@parndt

parndt commented Oct 20, 2026

Copy link
Copy Markdown
Collaborator

Ah, or you could pin the runner!

Comment thread spec/requests/session_timeout_spec.rb Outdated
Comment on lines +42 to +45
it "keeps tokens whose expiry matches the calendar-aware lifespan" do
3.times { sign_in_headers }
expect(user.reload.tokens.keys.length).to eq(2)
end

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This passes or fails depending on today's date. Like prunes rows when max_number_of_devices is exceeded, it only fails without the fix while "now + 2 weeks" crosses the end of BST
(roughly 11–25 Oct). From 26 Oct it also passes against the unfixed gem, so it won't catch a regression, for example after a devise_token_auth upgrade. As written it also repeats the
example above.

Suggest pinning the clock inside the window:

RSpec.describe "Session inactivity timeout", type: :request do
  include ActiveSupport::Testing::TimeHelpers
  # ...

    it "keeps tokens when the lifespan spans the end of BST" do
      # Within two weeks of the clocks going back, calendar-aware expiries sit
      # an hour above a flat-seconds ceiling.
      travel_to Time.zone.local(2026, 10, 20, 12) do
        3.times { sign_in_headers }
        expect(user.reload.tokens.keys.length).to eq(2)
      end
    end

Checked locally: passes with the override and fails without it (expected: 2, got: 0). It needs the TimeHelpers include because no spec here uses travel_to yet.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

May be better make the zone explicit so it works across deployments?

    it "keeps tokens when the lifespan spans a DST transition" do
      # The gem's flat-seconds ceiling diverges from a calendar-aware expiry
      # whenever a DST transition falls inside token_lifespan. Zone and date
      # pinned here so this holds regardless of how a deployment is configured.
      Time.use_zone("Edinburgh") do
        travel_to Time.zone.local(2026, 10, 20, 12) do
          3.times { sign_in_headers }
          expect(user.reload.tokens.keys.length).to eq(2)
        end
      end
    end

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, good point, agreed. master and nz-justice-development are on Pacific/Auckland, where two weeks from 20 Oct crosses no clock change, so my version would pass without the fix there. I checked yours locally: it fails without the override under both Edinburgh and Auckland configs (expected: 2, got: 0) and passes with it. Time.use_zone reaches the sign-in requests as hoped. It still needs include ActiveSupport::Testing::TimeHelpers in the describe block.

This branch was previously deployed

1 inactive deployment
sg-uat — cfc9072d Deployed Nov 12, 2026 by tmfrnz
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants