summaryrefslogtreecommitdiff
path: root/spec/models/active_session_spec.rb
blob: 27a80f93566783e0242cbe2c33c500348e50b63c (plain)
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
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe ActiveSession, :clean_gitlab_redis_shared_state do
  let(:user) do
    create(:user).tap do |user|
      user.current_sign_in_at = Time.current
    end
  end

  let(:session) do
    double(:session, { id: '6919a6f1bb119dd7396fadc38fd18d0d',
                       '[]': {} })
  end

  let(:request) do
    double(:request, {
      user_agent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 8_1_3 like Mac OS X) AppleWebKit/600.1.4 ' \
        '(KHTML, like Gecko) Mobile/12B466 [FBDV/iPhone7,2]',
      ip: '127.0.0.1',
      session: session
    })
  end

  describe '#current?' do
    it 'returns true if the active session matches the current session' do
      active_session = ActiveSession.new(session_id: '6919a6f1bb119dd7396fadc38fd18d0d')

      expect(active_session.current?(session)).to be true
    end

    it 'returns false if the active session does not match the current session' do
      active_session = ActiveSession.new(session_id: '59822c7d9fcdfa03725eff41782ad97d')

      expect(active_session.current?(session)).to be false
    end

    it 'returns false if the session id is nil' do
      active_session = ActiveSession.new(session_id: nil)
      session = double(:session, id: nil)

      expect(active_session.current?(session)).to be false
    end
  end

  describe '#public_id' do
    it 'returns an encrypted, url-encoded session id' do
      original_session_id = "!*'();:@&\n=+$,/?%abcd#123[4567]8"
      active_session = ActiveSession.new(session_id: original_session_id)
      encrypted_encoded_id = active_session.public_id

      encrypted_id = CGI.unescape(encrypted_encoded_id)
      derived_session_id = Gitlab::CryptoHelper.aes256_gcm_decrypt(encrypted_id)

      expect(original_session_id).to eq derived_session_id
    end
  end

  describe '.list' do
    it 'returns all sessions by user' do
      Gitlab::Redis::SharedState.with do |redis|
        redis.set("session:user:gitlab:#{user.id}:6919a6f1bb119dd7396fadc38fd18d0d", Marshal.dump({ session_id: 'a' }))
        redis.set("session:user:gitlab:#{user.id}:59822c7d9fcdfa03725eff41782ad97d", Marshal.dump({ session_id: 'b' }))
        redis.set("session:user:gitlab:9999:5c8611e4f9c69645ad1a1492f4131358", '')

        redis.sadd(
          "session:lookup:user:gitlab:#{user.id}",
          %w[
            6919a6f1bb119dd7396fadc38fd18d0d
            59822c7d9fcdfa03725eff41782ad97d
          ]
        )
      end

      expect(ActiveSession.list(user)).to match_array [{ session_id: 'a' }, { session_id: 'b' }]
    end

    it 'does not return obsolete entries and cleans them up' do
      Gitlab::Redis::SharedState.with do |redis|
        redis.set("session:user:gitlab:#{user.id}:6919a6f1bb119dd7396fadc38fd18d0d", Marshal.dump({ session_id: 'a' }))

        redis.sadd(
          "session:lookup:user:gitlab:#{user.id}",
          %w[
            6919a6f1bb119dd7396fadc38fd18d0d
            59822c7d9fcdfa03725eff41782ad97d
          ]
        )
      end

      expect(ActiveSession.list(user)).to eq [{ session_id: 'a' }]

      Gitlab::Redis::SharedState.with do |redis|
        expect(redis.sscan_each("session:lookup:user:gitlab:#{user.id}").to_a).to eq ['6919a6f1bb119dd7396fadc38fd18d0d']
      end
    end

    it 'returns an empty array if the use does not have any active session' do
      expect(ActiveSession.list(user)).to eq []
    end
  end

  describe '.list_sessions' do
    it 'uses the ActiveSession lookup to return original sessions' do
      Gitlab::Redis::SharedState.with do |redis|
        redis.set("session:gitlab:6919a6f1bb119dd7396fadc38fd18d0d", Marshal.dump({ _csrf_token: 'abcd' }))

        redis.sadd(
          "session:lookup:user:gitlab:#{user.id}",
          %w[
            6919a6f1bb119dd7396fadc38fd18d0d
            59822c7d9fcdfa03725eff41782ad97d
          ]
        )
      end

      expect(ActiveSession.list_sessions(user)).to eq [{ _csrf_token: 'abcd' }]
    end
  end

  describe '.session_ids_for_user' do
    it 'uses the user lookup table to return session ids' do
      session_ids = ['59822c7d9fcdfa03725eff41782ad97d']

      Gitlab::Redis::SharedState.with do |redis|
        redis.sadd("session:lookup:user:gitlab:#{user.id}", session_ids)
      end

      expect(ActiveSession.session_ids_for_user(user.id)).to eq(session_ids)
    end
  end

  describe '.sessions_from_ids' do
    it 'uses the ActiveSession lookup to return original sessions' do
      Gitlab::Redis::SharedState.with do |redis|
        redis.set("session:gitlab:6919a6f1bb119dd7396fadc38fd18d0d", Marshal.dump({ _csrf_token: 'abcd' }))
      end

      expect(ActiveSession.sessions_from_ids(['6919a6f1bb119dd7396fadc38fd18d0d'])).to eq [{ _csrf_token: 'abcd' }]
    end

    it 'avoids a redis lookup for an empty array' do
      expect(Gitlab::Redis::SharedState).not_to receive(:with)

      expect(ActiveSession.sessions_from_ids([])).to eq([])
    end

    it 'uses redis lookup in batches' do
      stub_const('ActiveSession::SESSION_BATCH_SIZE', 1)

      redis = double(:redis)
      expect(Gitlab::Redis::SharedState).to receive(:with).and_yield(redis)

      sessions = %w[session-a session-b]
      mget_responses = sessions.map { |session| [Marshal.dump(session)]}
      expect(redis).to receive(:mget).twice.and_return(*mget_responses)

      expect(ActiveSession.sessions_from_ids([1, 2])).to eql(sessions)
    end
  end

  describe '.set' do
    it 'sets a new redis entry for the user session and a lookup entry' do
      ActiveSession.set(user, request)

      Gitlab::Redis::SharedState.with do |redis|
        expect(redis.scan_each.to_a).to include(
          "session:user:gitlab:#{user.id}:6919a6f1bb119dd7396fadc38fd18d0d",
          "session:lookup:user:gitlab:#{user.id}"
        )
      end
    end

    it 'adds timestamps and information from the request' do
      Timecop.freeze(Time.zone.parse('2018-03-12 09:06')) do
        ActiveSession.set(user, request)

        session = ActiveSession.list(user)

        expect(session.count).to eq 1
        expect(session.first).to have_attributes(
          ip_address: '127.0.0.1',
          browser: 'Mobile Safari',
          os: 'iOS',
          device_name: 'iPhone 6',
          device_type: 'smartphone',
          created_at: Time.zone.parse('2018-03-12 09:06'),
          updated_at: Time.zone.parse('2018-03-12 09:06')
        )
      end
    end

    it 'keeps the created_at from the login on consecutive requests' do
      now = Time.zone.parse('2018-03-12 09:06')

      Timecop.freeze(now) do
        ActiveSession.set(user, request)

        Timecop.freeze(now + 1.minute) do
          ActiveSession.set(user, request)

          session = ActiveSession.list(user)

          expect(session.first).to have_attributes(
            created_at: Time.zone.parse('2018-03-12 09:06'),
            updated_at: Time.zone.parse('2018-03-12 09:07')
          )
        end
      end
    end
  end

  describe '.destroy' do
    it 'removes the entry associated with the currently killed user session' do
      Gitlab::Redis::SharedState.with do |redis|
        redis.set("session:user:gitlab:#{user.id}:6919a6f1bb119dd7396fadc38fd18d0d", '')
        redis.set("session:user:gitlab:#{user.id}:59822c7d9fcdfa03725eff41782ad97d", '')
        redis.set("session:user:gitlab:9999:5c8611e4f9c69645ad1a1492f4131358", '')
      end

      ActiveSession.destroy(user, request.session.id)

      Gitlab::Redis::SharedState.with do |redis|
        expect(redis.scan_each(match: "session:user:gitlab:*")).to match_array [
          "session:user:gitlab:#{user.id}:59822c7d9fcdfa03725eff41782ad97d",
          "session:user:gitlab:9999:5c8611e4f9c69645ad1a1492f4131358"
        ]
      end
    end

    it 'removes the lookup entry' do
      Gitlab::Redis::SharedState.with do |redis|
        redis.set("session:user:gitlab:#{user.id}:6919a6f1bb119dd7396fadc38fd18d0d", '')
        redis.sadd("session:lookup:user:gitlab:#{user.id}", '6919a6f1bb119dd7396fadc38fd18d0d')
      end

      ActiveSession.destroy(user, request.session.id)

      Gitlab::Redis::SharedState.with do |redis|
        expect(redis.scan_each(match: "session:lookup:user:gitlab:#{user.id}").to_a).to be_empty
      end
    end

    it 'removes the devise session' do
      Gitlab::Redis::SharedState.with do |redis|
        redis.set("session:user:gitlab:#{user.id}:6919a6f1bb119dd7396fadc38fd18d0d", '')
        redis.set("session:gitlab:6919a6f1bb119dd7396fadc38fd18d0d", '')
      end

      ActiveSession.destroy(user, request.session.id)

      Gitlab::Redis::SharedState.with do |redis|
        expect(redis.scan_each(match: "session:gitlab:*").to_a).to be_empty
      end
    end
  end

  describe '.destroy_with_public_id' do
    it 'receives a user and public id and destroys the associated session' do
      ActiveSession.set(user, request)
      session = ActiveSession.list(user).first

      ActiveSession.destroy_with_public_id(user, session.public_id)

      total_sessions = ActiveSession.list(user).count
      expect(total_sessions).to eq 0
    end

    it 'handles invalid input for public id' do
      expect do
        ActiveSession.destroy_with_public_id(user, nil)
      end.not_to raise_error

      expect do
        ActiveSession.destroy_with_public_id(user, "")
      end.not_to raise_error

      expect do
        ActiveSession.destroy_with_public_id(user, "aaaaaaaa")
      end.not_to raise_error
    end

    it 'does not attempt to destroy session when given invalid input for public id' do
      expect(ActiveSession).not_to receive(:destroy)

      ActiveSession.destroy_with_public_id(user, nil)
      ActiveSession.destroy_with_public_id(user, "")
      ActiveSession.destroy_with_public_id(user, "aaaaaaaa")
    end
  end

  describe '.cleanup' do
    before do
      stub_const("ActiveSession::ALLOWED_NUMBER_OF_ACTIVE_SESSIONS", 5)
    end

    it 'removes obsolete lookup entries' do
      Gitlab::Redis::SharedState.with do |redis|
        redis.set("session:user:gitlab:#{user.id}:6919a6f1bb119dd7396fadc38fd18d0d", '')
        redis.sadd("session:lookup:user:gitlab:#{user.id}", '6919a6f1bb119dd7396fadc38fd18d0d')
        redis.sadd("session:lookup:user:gitlab:#{user.id}", '59822c7d9fcdfa03725eff41782ad97d')
      end

      ActiveSession.cleanup(user)

      Gitlab::Redis::SharedState.with do |redis|
        expect(redis.smembers("session:lookup:user:gitlab:#{user.id}")).to eq ['6919a6f1bb119dd7396fadc38fd18d0d']
      end
    end

    it 'does not bail if there are no lookup entries' do
      ActiveSession.cleanup(user)
    end

    context 'cleaning up old sessions' do
      let(:max_number_of_sessions_plus_one) { ActiveSession::ALLOWED_NUMBER_OF_ACTIVE_SESSIONS + 1 }
      let(:max_number_of_sessions_plus_two) { ActiveSession::ALLOWED_NUMBER_OF_ACTIVE_SESSIONS + 2 }

      before do
        Gitlab::Redis::SharedState.with do |redis|
          (1..max_number_of_sessions_plus_two).each do |number|
            redis.set(
              "session:user:gitlab:#{user.id}:#{number}",
              Marshal.dump(ActiveSession.new(session_id: "#{number}", updated_at: number.days.ago))
            )
            redis.sadd(
              "session:lookup:user:gitlab:#{user.id}",
              "#{number}"
            )
          end
        end
      end

      it 'removes obsolete active sessions entries' do
        ActiveSession.cleanup(user)

        Gitlab::Redis::SharedState.with do |redis|
          sessions = redis.scan_each(match: "session:user:gitlab:#{user.id}:*").to_a

          expect(sessions.count).to eq(ActiveSession::ALLOWED_NUMBER_OF_ACTIVE_SESSIONS)
          expect(sessions).not_to include("session:user:gitlab:#{user.id}:#{max_number_of_sessions_plus_one}", "session:user:gitlab:#{user.id}:#{max_number_of_sessions_plus_two}")
        end
      end

      it 'removes obsolete lookup entries' do
        ActiveSession.cleanup(user)

        Gitlab::Redis::SharedState.with do |redis|
          lookup_entries = redis.smembers("session:lookup:user:gitlab:#{user.id}")

          expect(lookup_entries.count).to eq(ActiveSession::ALLOWED_NUMBER_OF_ACTIVE_SESSIONS)
          expect(lookup_entries).not_to include(max_number_of_sessions_plus_one.to_s, max_number_of_sessions_plus_two.to_s)
        end
      end

      it 'removes obsolete lookup entries even without active session' do
        Gitlab::Redis::SharedState.with do |redis|
          redis.sadd(
            "session:lookup:user:gitlab:#{user.id}",
            "#{max_number_of_sessions_plus_two + 1}"
          )
        end

        ActiveSession.cleanup(user)

        Gitlab::Redis::SharedState.with do |redis|
          lookup_entries = redis.smembers("session:lookup:user:gitlab:#{user.id}")

          expect(lookup_entries.count).to eq(ActiveSession::ALLOWED_NUMBER_OF_ACTIVE_SESSIONS)
          expect(lookup_entries).not_to include(
            max_number_of_sessions_plus_one.to_s,
            max_number_of_sessions_plus_two.to_s,
            (max_number_of_sessions_plus_two + 1).to_s
          )
        end
      end

      context 'when the number of active sessions is lower than the limit' do
        before do
          Gitlab::Redis::SharedState.with do |redis|
            ((max_number_of_sessions_plus_two - 4)..max_number_of_sessions_plus_two).each do |number|
              redis.del("session:user:gitlab:#{user.id}:#{number}")
            end
          end
        end

        it 'does not remove active session entries, but removes lookup entries' do
          lookup_entries_before_cleanup = Gitlab::Redis::SharedState.with do |redis|
            redis.smembers("session:lookup:user:gitlab:#{user.id}")
          end

          sessions_before_cleanup = Gitlab::Redis::SharedState.with do |redis|
            redis.scan_each(match: "session:user:gitlab:#{user.id}:*").to_a
          end

          ActiveSession.cleanup(user)

          Gitlab::Redis::SharedState.with do |redis|
            lookup_entries = redis.smembers("session:lookup:user:gitlab:#{user.id}")
            sessions = redis.scan_each(match: "session:user:gitlab:#{user.id}:*").to_a
            expect(sessions.count).to eq(sessions_before_cleanup.count)
            expect(lookup_entries.count).to be < lookup_entries_before_cleanup.count
          end
        end
      end
    end
  end
end