Repository navigation
Expand file tree
/
Copy pathSessionServiceTest.java
More file actions
527 lines (431 loc) · 21 KB
/
Copy pathSessionServiceTest.java
File metadata and controls
527 lines (431 loc) · 21 KB
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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
package com.wallet.secure.auth.service;
import com.wallet.secure.auth.dto.SessionResponse;
import com.wallet.secure.auth.entity.Session;
import com.wallet.secure.auth.repository.SessionRepository;
import com.wallet.secure.auth.security.JwtService;
import com.wallet.secure.common.exception.InvalidCredentialsException;
import com.wallet.secure.common.exception.ResourceNotFoundException;
import com.wallet.secure.common.response.ApiResponse;
import com.wallet.secure.user.entity.User;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.time.Instant;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
/**
* Unit tests for SessionService.
*
* WHAT we test:
* 1. createSession() — builds entity with correct fields and hashes the token
* 2. validateSession() — rejects unknown, revoked and expired sessions
* 3. revokeByToken() — marks session as revoked, no-op when not found
* 4. revokeAllSessions() — delegates bulk update to repository
* 5. revokeSessionById() — ownership check (OWASP A01), already-revoked guard
* 6. getActiveSessions() — flags current session, handles null token
* 7. hashToken() — deterministic, 64-char hex output (SHA-256)
*
* WHAT we do NOT test:
* → @Transactional behavior — requires Spring context
* → Real SHA-256 correctness — guaranteed by the JVM spec
*/
@ExtendWith(MockitoExtension.class)
@DisplayName("SessionService")
class SessionServiceTest {
@Mock private SessionRepository sessionRepository;
@Mock private JwtService jwtService;
@InjectMocks
private SessionService sessionService;
// ─── Shared test data
private User testUser;
private UUID userId;
private UUID sessionId;
private static final String RAW_TOKEN = "test.refresh.token.device.A";
private static final String OTHER_TOKEN = "test.refresh.token.device.B";
private static final String TEST_IP = "192.168.1.100";
private static final String TEST_UA = "Mozilla/5.0 Test";
@BeforeEach
void setUp() {
userId = UUID.randomUUID();
sessionId = UUID.randomUUID();
testUser = User.builder()
.id(userId)
.email("angel@test.com")
.passwordHash("$2a$12$hashedpassword")
.build();
}
// ─── Helper — builds a minimal valid Session
private Session buildActiveSession(String rawToken) {
String hash = sessionService.hashToken(rawToken);
return Session.builder()
.user(testUser)
.tokenHash(hash)
.ipAddress(TEST_IP)
.userAgent(TEST_UA)
.expiresAt(Instant.now().plusSeconds(3600)) // expires in 1 hour
.build();
}
private Session buildRevokedSession(String rawToken) {
Session session = buildActiveSession(rawToken);
session.revokeNow();
return session;
}
private Session buildExpiredSession(String rawToken) {
String hash = sessionService.hashToken(rawToken);
return Session.builder()
.user(testUser)
.tokenHash(hash)
.ipAddress(TEST_IP)
.userAgent(TEST_UA)
.expiresAt(Instant.now().minusSeconds(60)) // expired 1 minute ago
.build();
}
// ─── createSession()
@Nested
@DisplayName("createSession()")
class CreateSessionTests {
@Test
@DisplayName("saves session with hashed token — raw token never stored in DB")
void createSession_savesHashedToken() {
// GIVEN
lenient().when(jwtService.getRefreshExpirationMs()).thenReturn(86_400_000L); // 1 day
when(sessionRepository.save(any(Session.class)))
.thenAnswer(inv -> inv.getArgument(0));
// WHEN
sessionService.createSession(testUser, RAW_TOKEN, TEST_IP, TEST_UA);
// THEN — capture what was saved
ArgumentCaptor<Session> captor = ArgumentCaptor.forClass(Session.class);
verify(sessionRepository).save(captor.capture());
Session saved = captor.getValue();
// OWASP A02: raw token is NEVER stored — only the SHA-256 hash
assertThat(saved.getTokenHash()).isNotEqualTo(RAW_TOKEN);
assertThat(saved.getTokenHash()).isEqualTo(sessionService.hashToken(RAW_TOKEN));
assertThat(saved.getTokenHash()).hasSize(64); // SHA-256 in hex = 64 chars
}
@Test
@DisplayName("saves session with correct user, ip and userAgent")
void createSession_savesCorrectContext() {
// GIVEN
lenient().when(jwtService.getRefreshExpirationMs()).thenReturn(86_400_000L);
when(sessionRepository.save(any(Session.class)))
.thenAnswer(inv -> inv.getArgument(0));
// WHEN
sessionService.createSession(testUser, RAW_TOKEN, TEST_IP, TEST_UA);
// THEN
ArgumentCaptor<Session> captor = ArgumentCaptor.forClass(Session.class);
verify(sessionRepository).save(captor.capture());
Session saved = captor.getValue();
assertThat(saved.getUser()).isEqualTo(testUser);
assertThat(saved.getIpAddress()).isEqualTo(TEST_IP);
assertThat(saved.getUserAgent()).isEqualTo(TEST_UA);
assertThat(saved.getExpiresAt()).isAfter(Instant.now());
}
}
// ─── validateSession()
@Nested
@DisplayName("validateSession()")
class ValidateSessionTests {
@Test
@DisplayName("returns session when token is valid and not expired")
void validateSession_validToken_returnsSession() {
// GIVEN
Session activeSession = buildActiveSession(RAW_TOKEN);
when(sessionRepository.findByTokenHash(sessionService.hashToken(RAW_TOKEN)))
.thenReturn(Optional.of(activeSession));
// WHEN
Session result = sessionService.validateSession(RAW_TOKEN);
// THEN
assertThat(result).isEqualTo(activeSession);
}
@Test
@DisplayName("throws when session is not found — possible token reuse after logout")
void validateSession_sessionNotFound_throwsException() {
// GIVEN — token was never issued or was deleted
when(sessionRepository.findByTokenHash(any())).thenReturn(Optional.empty());
// WHEN / THEN
// OWASP A07: unknown token = definitive rejection
assertThatThrownBy(() -> sessionService.validateSession(RAW_TOKEN))
.isInstanceOf(InvalidCredentialsException.class)
.hasMessageContaining("revoked");
}
@Test
@DisplayName("rejects a stored token hash when presented as a refresh token — OWASP A02")
void validateSession_storedHashCannotBeUsedAsRefreshToken() {
// GIVEN — an attacker obtained the database value, not the raw JWT.
String storedHash = sessionService.hashToken(RAW_TOKEN);
String lookupHash = sessionService.hashToken(storedHash);
when(sessionRepository.findByTokenHash(lookupHash)).thenReturn(Optional.empty());
// WHEN / THEN — validateSession hashes the supplied value again.
assertThatThrownBy(() -> sessionService.validateSession(storedHash))
.isInstanceOf(InvalidCredentialsException.class)
.hasMessageContaining("revoked");
verify(sessionRepository).findByTokenHash(lookupHash);
}
@Test
@DisplayName("throws when session is revoked — user already logged out")
void validateSession_revokedSession_throwsException() {
// GIVEN — user called logout → session was marked revoked
Session revokedSession = buildRevokedSession(RAW_TOKEN);
when(sessionRepository.findByTokenHash(any()))
.thenReturn(Optional.of(revokedSession));
// WHEN / THEN
// OWASP A07: revoked token cannot refresh — even with valid JWT signature
assertThatThrownBy(() -> sessionService.validateSession(RAW_TOKEN))
.isInstanceOf(InvalidCredentialsException.class)
.hasMessageContaining("revoked or expired");
}
@Test
@DisplayName("throws when session is expired — natural expiration")
void validateSession_expiredSession_throwsException() {
// GIVEN — session was issued long ago and expiresAt < now
Session expiredSession = buildExpiredSession(RAW_TOKEN);
when(sessionRepository.findByTokenHash(any()))
.thenReturn(Optional.of(expiredSession));
// WHEN / THEN
assertThatThrownBy(() -> sessionService.validateSession(RAW_TOKEN))
.isInstanceOf(InvalidCredentialsException.class)
.hasMessageContaining("revoked or expired");
}
}
// ─── rotateSession()
@Nested
@DisplayName("rotateSession()")
class RotateSessionTests {
@Test
@DisplayName("consumes old session and saves a hashed replacement — OWASP A07")
void rotateSession_activeSession_revokesAndCreatesReplacement() {
// GIVEN
Session current = buildActiveSession(RAW_TOKEN);
when(sessionRepository.findByTokenHashWithLock(sessionService.hashToken(RAW_TOKEN)))
.thenReturn(Optional.of(current));
when(sessionRepository.save(any(Session.class))).thenAnswer(invocation -> invocation.getArgument(0));
when(jwtService.getRefreshExpirationMs()).thenReturn(86_400_000L);
// WHEN
sessionService.rotateSession(testUser, RAW_TOKEN, OTHER_TOKEN, TEST_IP, TEST_UA);
// THEN
assertThat(current.isRevoked()).isTrue();
verify(sessionRepository).save(current);
verify(sessionRepository).save(argThat(session ->
session.getTokenHash().equals(sessionService.hashToken(OTHER_TOKEN))));
}
@Test
@DisplayName("rejects consumed session while holding its lock — OWASP A07")
void rotateSession_revokedSession_throwsException() {
// GIVEN
Session consumed = buildRevokedSession(RAW_TOKEN);
when(sessionRepository.findByTokenHashWithLock(sessionService.hashToken(RAW_TOKEN)))
.thenReturn(Optional.of(consumed));
// WHEN / THEN
assertThatThrownBy(() -> sessionService.rotateSession(testUser, RAW_TOKEN, OTHER_TOKEN, TEST_IP, TEST_UA))
.isInstanceOf(InvalidCredentialsException.class)
.hasMessageContaining("revoked or expired");
verify(sessionRepository, never()).save(any());
}
}
// ─── revokeByToken()
@Nested
@DisplayName("revokeByToken()")
class RevokeByTokenTests {
@Test
@DisplayName("marks session as revoked when found")
void revokeByToken_sessionFound_revokesSession() {
// GIVEN
Session activeSession = buildActiveSession(RAW_TOKEN);
when(sessionRepository.findByTokenHash(sessionService.hashToken(RAW_TOKEN)))
.thenReturn(Optional.of(activeSession));
when(sessionRepository.save(any(Session.class)))
.thenAnswer(inv -> inv.getArgument(0));
// WHEN
sessionService.revokeByToken(RAW_TOKEN);
// THEN
assertThat(activeSession.isRevoked()).isTrue();
assertThat(activeSession.getRevokedAt()).isNotNull();
verify(sessionRepository).save(activeSession);
}
@Test
@DisplayName("does nothing (no-op) when session is not found — safe to call twice")
void revokeByToken_sessionNotFound_doesNotThrow() {
// GIVEN — token may have already expired and been cleaned up
when(sessionRepository.findByTokenHash(any())).thenReturn(Optional.empty());
// WHEN / THEN — must not throw; idempotent revocation
assertThatNoException().isThrownBy(() -> sessionService.revokeByToken(RAW_TOKEN));
verify(sessionRepository, never()).save(any());
}
}
// ─── revokeAllSessions()
@Nested
@DisplayName("revokeAllSessions()")
class RevokeAllSessionsTests {
@Test
@DisplayName("delegates bulk revocation to repository with userId and current time")
void revokeAllSessions_delegatesToRepository() {
// GIVEN — no return value needed for @Modifying query
doNothing().when(sessionRepository)
.revokeAllActiveSessionsForUser(any(UUID.class), any(Instant.class));
// WHEN
sessionService.revokeAllSessions(userId);
// THEN — bulk update is issued once with the correct userId
ArgumentCaptor<Instant> timeCaptor = ArgumentCaptor.forClass(Instant.class);
verify(sessionRepository).revokeAllActiveSessionsForUser(eq(userId), timeCaptor.capture());
// The Instant passed must be "now" — allow 5 seconds of tolerance
Instant revokedAt = timeCaptor.getValue();
assertThat(revokedAt).isBefore(Instant.now().plusSeconds(1));
assertThat(revokedAt).isAfter(Instant.now().minusSeconds(5));
}
}
// ─── revokeSessionById()
@Nested
@DisplayName("revokeSessionById()")
class RevokeSessionByIdTests {
@Test
@DisplayName("revokes session when it belongs to the requesting user — OWASP A01")
void revokeSessionById_owner_revokesSuccessfully() {
// GIVEN
Session activeSession = buildActiveSession(RAW_TOKEN);
when(sessionRepository.findById(sessionId))
.thenReturn(Optional.of(activeSession));
when(sessionRepository.save(any(Session.class)))
.thenAnswer(inv -> inv.getArgument(0));
// Inject a UUID field into the session for the test
// Session.id is set by the DB — we need to simulate it here
// We test ownership via User.id comparison, not Session.id
// WHEN
ApiResponse<Void> response = sessionService.revokeSessionById(sessionId, userId);
// THEN
assertThat(response.isSuccess()).isTrue();
assertThat(activeSession.isRevoked()).isTrue();
}
@Test
@DisplayName("throws 404 when session does not exist")
void revokeSessionById_sessionNotFound_throwsNotFoundException() {
// GIVEN
when(sessionRepository.findById(sessionId)).thenReturn(Optional.empty());
// WHEN / THEN
assertThatThrownBy(() -> sessionService.revokeSessionById(sessionId, userId))
.isInstanceOf(ResourceNotFoundException.class)
.hasMessageContaining("Session not found");
}
@Test
@DisplayName("throws 401 when session belongs to a different user — OWASP A01")
void revokeSessionById_differentUser_throwsUnauthorized() {
// GIVEN — session belongs to testUser but attacker uses their own userId
UUID attackerId = UUID.randomUUID();
Session victimSession = buildActiveSession(RAW_TOKEN);
when(sessionRepository.findById(sessionId))
.thenReturn(Optional.of(victimSession));
// WHEN / THEN
// OWASP A01: user cannot revoke another user's session
assertThatThrownBy(() -> sessionService.revokeSessionById(sessionId, attackerId))
.isInstanceOf(InvalidCredentialsException.class)
.hasMessageContaining("Not authorized");
verify(sessionRepository, never()).save(any());
}
@Test
@DisplayName("returns success without re-revoking when session is already revoked")
void revokeSessionById_alreadyRevoked_returnsSuccessIdempotent() {
// GIVEN — session already revoked (user called this endpoint twice)
Session revokedSession = buildRevokedSession(RAW_TOKEN);
when(sessionRepository.findById(sessionId))
.thenReturn(Optional.of(revokedSession));
// WHEN
ApiResponse<Void> response = sessionService.revokeSessionById(sessionId, userId);
// THEN — idempotent: success, but no extra save()
assertThat(response.isSuccess()).isTrue();
verify(sessionRepository, never()).save(any());
}
}
// ─── getActiveSessions()
@Nested
@DisplayName("getActiveSessions()")
class GetActiveSessionsTests {
@Test
@DisplayName("flags the session matching currentRefreshToken as current=true")
void getActiveSessions_withMatchingToken_flagsCurrentSession() {
// GIVEN — two active sessions; first one belongs to the current request
Session currentSession = buildActiveSession(RAW_TOKEN);
Session otherSession = buildActiveSession(OTHER_TOKEN);
when(sessionRepository.findActiveSessionsByUserId(eq(userId), any(Instant.class)))
.thenReturn(List.of(currentSession, otherSession));
// WHEN
ApiResponse<List<SessionResponse>> response =
sessionService.getActiveSessions(userId, RAW_TOKEN);
// THEN
assertThat(response.isSuccess()).isTrue();
assertThat(response.getData()).hasSize(2);
// The session that matches the current token must be flagged
SessionResponse current = response.getData().get(0);
SessionResponse other = response.getData().get(1);
assertThat(current.isCurrent()).isTrue();
assertThat(other.isCurrent()).isFalse();
}
@Test
@DisplayName("returns current=false for all sessions when currentRefreshToken is null")
void getActiveSessions_nullToken_noSessionFlagged() {
// GIVEN — caller did not provide a current token (e.g. admin lookup)
Session session = buildActiveSession(RAW_TOKEN);
when(sessionRepository.findActiveSessionsByUserId(eq(userId), any(Instant.class)))
.thenReturn(List.of(session));
// WHEN
ApiResponse<List<SessionResponse>> response =
sessionService.getActiveSessions(userId, null);
// THEN — null token → no session can be flagged as current
assertThat(response.getData().get(0).isCurrent()).isFalse();
}
@Test
@DisplayName("returns empty list when user has no active sessions")
void getActiveSessions_noSessions_returnsEmptyList() {
// GIVEN
when(sessionRepository.findActiveSessionsByUserId(eq(userId), any(Instant.class)))
.thenReturn(List.of());
// WHEN
ApiResponse<List<SessionResponse>> response =
sessionService.getActiveSessions(userId, null);
// THEN
assertThat(response.isSuccess()).isTrue();
assertThat(response.getData()).isEmpty();
}
}
// ─── hashToken()
@Nested
@DisplayName("hashToken()")
class HashTokenTests {
@Test
@DisplayName("returns 64-character lowercase hex string — SHA-256 output")
void hashToken_returnsCorrectFormat() {
// WHEN
String hash = sessionService.hashToken(RAW_TOKEN);
// THEN — SHA-256 produces 32 bytes = 64 hex chars
assertThat(hash).hasSize(64);
assertThat(hash).matches("[0-9a-f]{64}");
}
@Test
@DisplayName("is deterministic — same input always produces the same hash")
void hashToken_deterministic_sameInputSameOutput() {
// WHEN
String hash1 = sessionService.hashToken(RAW_TOKEN);
String hash2 = sessionService.hashToken(RAW_TOKEN);
// THEN — SHA-256 is deterministic by definition
// OWASP A02: lookup by hash only works if hash is reproducible
assertThat(hash1).isEqualTo(hash2);
}
@Test
@DisplayName("different tokens produce different hashes — no collisions")
void hashToken_differentInputs_differentHashes() {
// WHEN
String hash1 = sessionService.hashToken(RAW_TOKEN);
String hash2 = sessionService.hashToken(OTHER_TOKEN);
// THEN — collision resistance: distinct tokens must not share a hash
assertThat(hash1).isNotEqualTo(hash2);
}
}
}