-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathUserAPIUnitTest.java
More file actions
1213 lines (1042 loc) · 60.5 KB
/
Copy pathUserAPIUnitTest.java
File metadata and controls
1213 lines (1042 loc) · 60.5 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
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
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
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package com.digitalsanctuary.spring.user.api;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.read.ListAppender;
import java.util.Collections;
import java.util.Locale;
import com.digitalsanctuary.spring.user.audit.AuditEvent;
import com.digitalsanctuary.spring.user.dto.PasswordDto;
import com.digitalsanctuary.spring.user.dto.SetPasswordDto;
import com.digitalsanctuary.spring.user.dto.UserDto;
import com.digitalsanctuary.spring.user.dto.UserProfileUpdateDto;
import com.digitalsanctuary.spring.user.security.StepUpService;
import java.util.List;
import org.springframework.beans.factory.ObjectProvider;
import com.digitalsanctuary.spring.user.event.OnRegistrationCompleteEvent;
import com.digitalsanctuary.spring.user.exceptions.InvalidOldPasswordException;
import com.digitalsanctuary.spring.user.exceptions.UserAlreadyExistException;
import com.digitalsanctuary.spring.user.persistence.model.User;
import com.digitalsanctuary.spring.user.service.DSUserDetails;
import com.digitalsanctuary.spring.user.service.LoginAttemptService;
import com.digitalsanctuary.spring.user.service.PasswordPolicyService;
import com.digitalsanctuary.spring.user.service.UserEmailService;
import com.digitalsanctuary.spring.user.service.UserService;
import com.digitalsanctuary.spring.user.test.builders.UserTestDataBuilder;
import com.digitalsanctuary.spring.user.util.AppUrlResolver;
import com.digitalsanctuary.spring.user.util.JSONResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.AfterEach;
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 org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.MessageSource;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.method.annotation.AuthenticationPrincipalArgumentResolver;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
@ExtendWith(MockitoExtension.class)
@DisplayName("UserAPI Unit Tests")
public class UserAPIUnitTest {
private MockMvc mockMvc;
/**
* Test exception handler to properly handle SecurityException in unit tests
*/
@RestControllerAdvice
static class TestExceptionHandler {
@ExceptionHandler(SecurityException.class)
public JSONResponse handleSecurityException(SecurityException e) {
return JSONResponse.builder()
.success(false)
.code(401)
.message(e.getMessage())
.build();
}
}
private ObjectMapper objectMapper = new ObjectMapper();
@Mock
private UserService userService;
@Mock
private UserEmailService userEmailService;
@Mock
private MessageSource messageSource;
@Mock
private ApplicationEventPublisher eventPublisher;
@Mock
private PasswordPolicyService passwordPolicyService;
@Mock
private AppUrlResolver appUrlResolver;
@Mock
private LoginAttemptService loginAttemptService;
@InjectMocks
private UserAPI userAPI;
private User testUser;
private UserDto testUserDto;
private DSUserDetails testUserDetails;
@BeforeEach
void setUp() {
// Tests run in parallel (junit-platform.properties: concurrent methods + classes) with thread reuse, and the
// `_notAuthenticated` tests resolve @AuthenticationPrincipal from the thread-local SecurityContext (expecting it
// empty). Clear any context another test left on this thread so those tests are deterministic — matching the
// convention in UserServiceTest / WebAuthnAuthenticationSuccessHandlerTest / UserEmailServiceTest.
SecurityContextHolder.clearContext();
testUser = UserTestDataBuilder.aUser()
.withId(1L)
.withEmail("test@example.com")
.withFirstName("Test")
.withLastName("User")
.withPassword("encodedPassword")
.enabled()
.build();
testUserDto = new UserDto();
testUserDto.setEmail("test@example.com");
testUserDto.setFirstName("Test");
testUserDto.setLastName("User");
testUserDto.setPassword("password123");
testUserDto.setMatchingPassword("password123");
testUserDto.setRole(1);
testUserDetails = new DSUserDetails(testUser);
// Set field values using reflection
ReflectionTestUtils.setField(userAPI, "registrationPendingURI", "/user/registration-pending.html");
ReflectionTestUtils.setField(userAPI, "registrationSuccessURI", "/user/registration-complete.html");
ReflectionTestUtils.setField(userAPI, "forgotPasswordPendingURI", "/user/forgot-password-pending.html");
// Build MockMvc with standalone setup, custom argument resolver, and exception handler
mockMvc = MockMvcBuilders.standaloneSetup(userAPI)
.setCustomArgumentResolvers(new AuthenticationPrincipalArgumentResolver())
.setControllerAdvice(new TestExceptionHandler())
.build();
}
@AfterEach
void tearDown() {
// Do not leak a SecurityContext onto this (pooled, reused) thread for a subsequently scheduled parallel test.
SecurityContextHolder.clearContext();
}
@Nested
@DisplayName("User Registration Tests")
class UserRegistrationTests {
@Test
@DisplayName("POST /user/registration - successful registration with verification email")
void registerUserAccount_success_withVerificationEmail() throws Exception {
// Given
User newUser = UserTestDataBuilder.aUser()
.withEmail(testUserDto.getEmail())
.withFirstName(testUserDto.getFirstName())
.withLastName(testUserDto.getLastName())
.disabled() // User not enabled until email verification
.build();
when(userService.registerNewUserAccount(any(UserDto.class))).thenReturn(newUser);
when(passwordPolicyService.validate(any(), anyString(), anyString(), any(Locale.class)))
.thenReturn(Collections.emptyList());
// When & Then
mockMvc.perform(post("/user/registration")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(testUserDto))
.with(csrf()))
.andExpect(status().isOk())
.andExpect(jsonPath("$.success").value(true))
.andExpect(jsonPath("$.code").value(0))
.andExpect(jsonPath("$.messages[0]")
.value("If your email address is eligible, you will receive a verification email shortly."))
.andExpect(jsonPath("$.redirectUrl").value("/user/registration-pending.html"));
// Verify event publishing
verify(eventPublisher, times(2)).publishEvent(any());
// Verify specific event types
ArgumentCaptor<OnRegistrationCompleteEvent> registrationCaptor = ArgumentCaptor.forClass(OnRegistrationCompleteEvent.class);
verify(eventPublisher).publishEvent(registrationCaptor.capture());
OnRegistrationCompleteEvent registrationEvent = registrationCaptor.getValue();
assertThat(registrationEvent.getUserEmail()).isEqualTo(newUser.getEmail());
assertThat(registrationEvent.isUserEnabled()).isEqualTo(newUser.isEnabled());
ArgumentCaptor<AuditEvent> auditCaptor = ArgumentCaptor.forClass(AuditEvent.class);
verify(eventPublisher).publishEvent(auditCaptor.capture());
AuditEvent auditEvent = auditCaptor.getValue();
assertThat(auditEvent.getAction()).isEqualTo("Registration");
assertThat(auditEvent.getActionStatus()).isEqualTo("Success");
}
@Test
@DisplayName("POST /user/registration - successful registration with auto-login")
void registerUserAccount_success_withAutoLogin() throws Exception {
// Given
User newUser = UserTestDataBuilder.aUser()
.withEmail(testUserDto.getEmail())
.enabled() // User is immediately enabled
.build();
when(userService.registerNewUserAccount(any(UserDto.class))).thenReturn(newUser);
when(passwordPolicyService.validate(any(), anyString(), anyString(), any(Locale.class)))
.thenReturn(Collections.emptyList());
// When & Then
mockMvc.perform(post("/user/registration")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(testUserDto))
.with(csrf()))
.andExpect(status().isOk())
.andExpect(jsonPath("$.success").value(true))
.andExpect(jsonPath("$.redirectUrl").value("/user/registration-complete.html"));
// Verify auto-login was called
verify(userService).authWithoutPassword(newUser);
}
@Test
@DisplayName("POST /user/registration - existing email returns the same uniform 200 body as a new registration")
void registerUserAccount_existingEmail_returnsUniformResponse() throws Exception {
// Given - the service signals the email is already registered
when(userService.registerNewUserAccount(any(UserDto.class)))
.thenThrow(new UserAlreadyExistException("User already exists"));
when(passwordPolicyService.validate(any(), anyString(), anyString(), any(Locale.class)))
.thenReturn(Collections.emptyList());
// When & Then - response is indistinguishable from a brand-new registration
mockMvc.perform(post("/user/registration")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(testUserDto))
.with(csrf()))
.andExpect(status().isOk())
.andExpect(jsonPath("$.success").value(true))
.andExpect(jsonPath("$.code").value(0))
.andExpect(jsonPath("$.messages[0]")
.value("If your email address is eligible, you will receive a verification email shortly."))
.andExpect(jsonPath("$.redirectUrl").value("/user/registration-pending.html"));
// No new account is created: no registration event is published and no auto-login occurs.
verify(eventPublisher, never()).publishEvent(any(OnRegistrationCompleteEvent.class));
verify(userService, never()).authWithoutPassword(any());
}
@Test
@DisplayName("POST /user/registration - missing email")
void registerUserAccount_missingEmail() throws Exception {
// Given
testUserDto.setEmail(null);
// When & Then - validation should reject null email with 400 Bad Request
mockMvc.perform(post("/user/registration")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(testUserDto))
.with(csrf()))
.andExpect(status().isBadRequest());
}
@Test
@DisplayName("POST /user/registration - missing password")
void registerUserAccount_missingPassword() throws Exception {
// Given
testUserDto.setPassword(null);
// When & Then - validation should reject null password with 400 Bad Request
mockMvc.perform(post("/user/registration")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(testUserDto))
.with(csrf()))
.andExpect(status().isBadRequest());
}
@Test
@DisplayName("POST /user/registration - unexpected error")
void registerUserAccount_unexpectedError() throws Exception {
// Given
when(userService.registerNewUserAccount(any(UserDto.class)))
.thenThrow(new RuntimeException("Database error"));
when(passwordPolicyService.validate(any(), anyString(), anyString(), any(Locale.class)))
.thenReturn(Collections.emptyList());
// When & Then
mockMvc.perform(post("/user/registration")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(testUserDto))
.with(csrf()))
.andExpect(status().isInternalServerError())
.andExpect(jsonPath("$.success").value(false))
.andExpect(jsonPath("$.code").value(5))
.andExpect(jsonPath("$.messages[0]").value("System Error!"));
}
}
@Nested
@DisplayName("Resend Registration Token Tests")
class ResendRegistrationTokenTests {
@Test
@DisplayName("POST /user/resendRegistrationToken - success")
void resendRegistrationToken_success() throws Exception {
// Given
User unverifiedUser = UserTestDataBuilder.aUser()
.withEmail(testUserDto.getEmail())
.disabled()
.build();
when(userService.findUserByEmail(testUserDto.getEmail())).thenReturn(unverifiedUser);
when(appUrlResolver.resolveAppUrl(any())).thenReturn("http://localhost:8080");
// When & Then
mockMvc.perform(post("/user/resendRegistrationToken")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(testUserDto))
.with(csrf()))
.andExpect(status().isOk())
.andExpect(jsonPath("$.success").value(true))
.andExpect(jsonPath("$.code").value(0))
.andExpect(jsonPath("$.messages[0]")
.value("If your account requires verification, a new verification email has been sent."));
verify(userEmailService).sendRegistrationVerificationEmail(eq(unverifiedUser), anyString());
}
@Test
@DisplayName("POST /user/resendRegistrationToken - already-verified account returns the same uniform 200 body")
void resendRegistrationToken_alreadyVerified_returnsUniformResponse() throws Exception {
// Given - an existing, already-enabled (verified) account
when(userService.findUserByEmail(testUserDto.getEmail())).thenReturn(testUser); // enabled user
// When & Then - same response as the unverified case, and no email is sent
mockMvc.perform(post("/user/resendRegistrationToken")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(testUserDto))
.with(csrf()))
.andExpect(status().isOk())
.andExpect(jsonPath("$.success").value(true))
.andExpect(jsonPath("$.code").value(0))
.andExpect(jsonPath("$.messages[0]")
.value("If your account requires verification, a new verification email has been sent."));
verify(userEmailService, never()).sendRegistrationVerificationEmail(any(User.class), anyString());
}
@Test
@DisplayName("POST /user/resendRegistrationToken - unknown email returns the same uniform 200 body (no 500 leak)")
void resendRegistrationToken_unknownEmail_returnsUniformResponse() throws Exception {
// Given - no account exists for the email
when(userService.findUserByEmail(testUserDto.getEmail())).thenReturn(null);
// When & Then - same uniform 200 response; nothing leaks existence
mockMvc.perform(post("/user/resendRegistrationToken")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(testUserDto))
.with(csrf()))
.andExpect(status().isOk())
.andExpect(jsonPath("$.success").value(true))
.andExpect(jsonPath("$.code").value(0))
.andExpect(jsonPath("$.messages[0]")
.value("If your account requires verification, a new verification email has been sent."));
verify(userEmailService, never()).sendRegistrationVerificationEmail(any(User.class), anyString());
}
}
@Nested
@DisplayName("Password Management Tests")
class PasswordManagementTests {
@Test
@DisplayName("POST /user/resetPassword - success")
void resetPassword_success() throws Exception {
// Given
when(userService.findUserByEmail(testUserDto.getEmail())).thenReturn(testUser);
when(appUrlResolver.resolveAppUrl(any())).thenReturn("http://localhost:8080");
// When & Then
mockMvc.perform(post("/user/resetPassword")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(testUserDto))
.with(csrf()))
.andExpect(status().isOk())
.andExpect(jsonPath("$.success").value(true))
.andExpect(jsonPath("$.messages[0]").value("If account exists, password reset email has been sent!"));
verify(userEmailService).sendForgotPasswordVerificationEmail(eq(testUser), anyString());
}
@Test
@DisplayName("POST /user/resetPassword - user not found (still returns success)")
void resetPassword_userNotFound() throws Exception {
// Given
when(userService.findUserByEmail(testUserDto.getEmail())).thenReturn(null);
// When & Then
mockMvc.perform(post("/user/resetPassword")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(testUserDto))
.with(csrf()))
.andExpect(status().isOk())
.andExpect(jsonPath("$.success").value(true))
.andExpect(jsonPath("$.messages[0]").value("If account exists, password reset email has been sent!"));
verify(userEmailService, never()).sendForgotPasswordVerificationEmail(any(), any());
}
@Test
@DisplayName("POST /user/updatePassword - success")
void updatePassword_success() throws Exception {
// Given
PasswordDto passwordDto = new PasswordDto();
passwordDto.setOldPassword("oldPassword");
passwordDto.setNewPassword("newPassword123");
// Mock the principal resolver to return our test user
mockMvc = MockMvcBuilders.standaloneSetup(userAPI)
.setCustomArgumentResolvers(new HandlerMethodArgumentResolver() {
@Override
public boolean supportsParameter(org.springframework.core.MethodParameter parameter) {
return parameter.getParameterType().equals(DSUserDetails.class);
}
@Override
public Object resolveArgument(org.springframework.core.MethodParameter parameter,
org.springframework.web.method.support.ModelAndViewContainer mavContainer,
org.springframework.web.context.request.NativeWebRequest webRequest,
org.springframework.web.bind.support.WebDataBinderFactory binderFactory) {
return testUserDetails;
}
})
.setControllerAdvice(new TestExceptionHandler())
.build();
when(userService.findUserByEmail(testUser.getEmail())).thenReturn(testUser);
when(userService.hasPassword(testUser)).thenReturn(true);
when(messageSource.getMessage(eq("message.update-password.success"), any(), any(), any(Locale.class)))
.thenReturn("Password updated successfully");
when(userService.checkIfValidOldPassword(any(User.class), eq("oldPassword"))).thenReturn(true);
// When & Then
mockMvc.perform(post("/user/updatePassword")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(passwordDto))
.with(csrf()))
.andExpect(status().isOk())
.andExpect(jsonPath("$.success").value(true))
.andExpect(jsonPath("$.messages[0]").value("Password updated successfully"));
verify(userService).changeUserPassword(eq(testUser), eq("newPassword123"));
}
@Test
@DisplayName("POST /user/updatePassword - invalid old password")
void updatePassword_invalidOldPassword() throws Exception {
// Given
PasswordDto passwordDto = new PasswordDto();
passwordDto.setOldPassword("wrongPassword");
passwordDto.setNewPassword("newPassword123");
// Mock the principal resolver to return our test user
mockMvc = MockMvcBuilders.standaloneSetup(userAPI)
.setCustomArgumentResolvers(new HandlerMethodArgumentResolver() {
@Override
public boolean supportsParameter(org.springframework.core.MethodParameter parameter) {
return parameter.getParameterType().equals(DSUserDetails.class);
}
@Override
public Object resolveArgument(org.springframework.core.MethodParameter parameter,
org.springframework.web.method.support.ModelAndViewContainer mavContainer,
org.springframework.web.context.request.NativeWebRequest webRequest,
org.springframework.web.bind.support.WebDataBinderFactory binderFactory) {
return testUserDetails;
}
})
.setControllerAdvice(new TestExceptionHandler())
.build();
when(userService.findUserByEmail(testUser.getEmail())).thenReturn(testUser);
when(userService.hasPassword(testUser)).thenReturn(true);
when(messageSource.getMessage(eq("message.update-password.invalid-old"), any(), any(), any(Locale.class)))
.thenReturn("Invalid old password");
when(userService.checkIfValidOldPassword(any(User.class), eq("wrongPassword"))).thenReturn(false);
// When & Then
mockMvc.perform(post("/user/updatePassword")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(passwordDto))
.with(csrf()))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.success").value(false))
.andExpect(jsonPath("$.code").value(1))
.andExpect(jsonPath("$.messages[0]").value("Invalid old password"));
}
/**
* Builds a standalone MockMvc that resolves the {@code @AuthenticationPrincipal} argument to
* {@link #testUserDetails}, matching the setup the other updatePassword tests use inline.
*/
private MockMvc updatePasswordMockMvc() {
return MockMvcBuilders.standaloneSetup(userAPI)
.setCustomArgumentResolvers(new HandlerMethodArgumentResolver() {
@Override
public boolean supportsParameter(org.springframework.core.MethodParameter parameter) {
return parameter.getParameterType().equals(DSUserDetails.class);
}
@Override
public Object resolveArgument(org.springframework.core.MethodParameter parameter,
org.springframework.web.method.support.ModelAndViewContainer mavContainer,
org.springframework.web.context.request.NativeWebRequest webRequest,
org.springframework.web.bind.support.WebDataBinderFactory binderFactory) {
return testUserDetails;
}
})
.setControllerAdvice(new TestExceptionHandler())
.build();
}
@Test
@DisplayName("POST /user/updatePassword - wrong old password is recorded for lockout")
void updatePassword_wrongOldPassword_recordsFailedAttempt() throws Exception {
PasswordDto passwordDto = new PasswordDto();
passwordDto.setOldPassword("wrongPassword");
passwordDto.setNewPassword("newPassword123");
mockMvc = updatePasswordMockMvc();
when(userService.findUserByEmail(testUser.getEmail())).thenReturn(testUser);
when(userService.hasPassword(testUser)).thenReturn(true);
when(messageSource.getMessage(eq("message.update-password.invalid-old"), any(), any(), any(Locale.class)))
.thenReturn("Invalid old password");
when(userService.checkIfValidOldPassword(any(User.class), eq("wrongPassword"))).thenReturn(false);
mockMvc.perform(post("/user/updatePassword")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(passwordDto))
.with(csrf()))
.andExpect(status().isBadRequest());
// A wrong current-password guess must count toward brute-force lockout, like the login path.
verify(loginAttemptService).loginFailed(testUser.getEmail());
verify(userService, never()).changeUserPassword(any(), any());
}
@Test
@DisplayName("POST /user/updatePassword - successful change resets the lockout counter")
void updatePassword_success_resetsLockoutCounter() throws Exception {
PasswordDto passwordDto = new PasswordDto();
passwordDto.setOldPassword("oldPassword");
passwordDto.setNewPassword("newPassword123");
mockMvc = updatePasswordMockMvc();
when(userService.findUserByEmail(testUser.getEmail())).thenReturn(testUser);
when(userService.hasPassword(testUser)).thenReturn(true);
when(messageSource.getMessage(eq("message.update-password.success"), any(), any(), any(Locale.class)))
.thenReturn("Password updated successfully");
when(userService.checkIfValidOldPassword(any(User.class), eq("oldPassword"))).thenReturn(true);
mockMvc.perform(post("/user/updatePassword")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(passwordDto))
.with(csrf()))
.andExpect(status().isOk());
// Correct reauthentication clears the failed-attempt counter, matching login semantics.
verify(loginAttemptService).loginSucceeded(testUser.getEmail());
verify(loginAttemptService, never()).loginFailed(any());
}
@Test
@DisplayName("POST /user/updatePassword - locked account is rejected with 423 without touching the password")
void updatePassword_lockedAccount_returnsLocked() throws Exception {
PasswordDto passwordDto = new PasswordDto();
passwordDto.setOldPassword("oldPassword");
passwordDto.setNewPassword("newPassword123");
mockMvc = updatePasswordMockMvc();
when(userService.findUserByEmail(testUser.getEmail())).thenReturn(testUser);
when(userService.hasPassword(testUser)).thenReturn(true);
when(loginAttemptService.isLocked(testUser.getEmail())).thenReturn(true);
when(messageSource.getMessage(eq("message.update-password.account-locked"), any(), any(), any(Locale.class)))
.thenReturn("Account is locked");
mockMvc.perform(post("/user/updatePassword")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(passwordDto))
.with(csrf()))
.andExpect(status().isLocked())
.andExpect(jsonPath("$.success").value(false))
.andExpect(jsonPath("$.code").value(3));
verify(userService, never()).checkIfValidOldPassword(any(), any());
verify(userService, never()).changeUserPassword(any(), any());
}
@Test
@DisplayName("POST /user/updatePassword - passwordless account is rejected without feeding the lockout counter")
void updatePassword_passwordlessAccount_rejectedWithoutLockout() throws Exception {
PasswordDto passwordDto = new PasswordDto();
passwordDto.setOldPassword("anything");
passwordDto.setNewPassword("newPassword123");
mockMvc = updatePasswordMockMvc();
when(userService.findUserByEmail(testUser.getEmail())).thenReturn(testUser);
// Passwordless (passkey-only / OAuth-only) account: no password is set.
when(userService.hasPassword(testUser)).thenReturn(false);
when(messageSource.getMessage(eq("message.update-password.no-password"), any(), any(), any(Locale.class)))
.thenReturn("No password is set on this account. Use the set password feature instead.");
mockMvc.perform(post("/user/updatePassword")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(passwordDto))
.with(csrf()))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.success").value(false))
.andExpect(jsonPath("$.code").value(4));
// A passwordless account has no current password to guess, so this endpoint must never report a failed
// attempt — otherwise any authenticated (or session-hijacking) caller could lock the account out of every
// auth method by hammering this endpoint. The guard also short-circuits before the lockout check itself.
verify(loginAttemptService, never()).loginFailed(any());
verify(loginAttemptService, never()).isLocked(any());
verify(userService, never()).checkIfValidOldPassword(any(), any());
verify(userService, never()).changeUserPassword(any(), any());
}
@Test
@DisplayName("POST /user/updatePassword - not authenticated")
void updatePassword_notAuthenticated() throws Exception {
// Given
PasswordDto passwordDto = new PasswordDto();
passwordDto.setOldPassword("oldPassword");
passwordDto.setNewPassword("newPassword123");
// When & Then
mockMvc.perform(post("/user/updatePassword")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(passwordDto))
.with(csrf()))
.andExpect(status().isOk())
.andExpect(jsonPath("$.success").value(false))
.andExpect(jsonPath("$.code").value(401))
.andExpect(jsonPath("$.messages[0]").value("User not logged in."));
}
// ---- SUF-02: /user/setPassword step-up guard ----
@SuppressWarnings("unchecked")
private ObjectProvider<StepUpService> stepUpProvider(StepUpService service) {
ObjectProvider<StepUpService> provider = mock(ObjectProvider.class);
when(provider.getIfAvailable()).thenReturn(service);
return provider;
}
private SetPasswordDto newSetPasswordDto() {
SetPasswordDto dto = new SetPasswordDto();
dto.setNewPassword("NewValidPass1!");
dto.setConfirmPassword("NewValidPass1!");
return dto;
}
@Test
@DisplayName("POST /user/setPassword - disabled by default when no StepUpService is configured")
void setPassword_noStepUpService_disabledByDefault() throws Exception {
mockMvc = updatePasswordMockMvc();
when(userService.findUserByEmail(testUser.getEmail())).thenReturn(testUser);
when(userService.hasPassword(testUser)).thenReturn(false);
ReflectionTestUtils.setField(userAPI, "stepUpServiceProvider", stepUpProvider(null));
when(messageSource.getMessage(eq("message.set-password.disabled"), any(), any(), any(Locale.class)))
.thenReturn("Setting an initial password is not enabled on this server.");
mockMvc.perform(post("/user/setPassword")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(newSetPasswordDto()))
.with(csrf()))
.andExpect(status().isForbidden())
.andExpect(jsonPath("$.success").value(false))
// Distinct code from the step-up-denied (401) branch so a client can disambiguate "disabled" from "denied".
.andExpect(jsonPath("$.code").value(7));
// Endpoint disabled by default: no step-up service, opt-in flag off -> the credential is never set.
verify(userService, never()).setInitialPassword(any(), any());
}
@Test
@DisplayName("POST /user/setPassword - allowed session-only when the opt-in flag is enabled")
void setPassword_noStepUpService_allowedWhenFlagEnabled() throws Exception {
mockMvc = updatePasswordMockMvc();
when(userService.findUserByEmail(testUser.getEmail())).thenReturn(testUser);
when(userService.hasPassword(testUser)).thenReturn(false);
ReflectionTestUtils.setField(userAPI, "stepUpServiceProvider", stepUpProvider(null));
ReflectionTestUtils.setField(userAPI, "allowInitialPasswordSetWithoutStepUp", true);
when(passwordPolicyService.validate(eq(testUser), eq("NewValidPass1!"), eq(testUser.getEmail()), any(Locale.class)))
.thenReturn(List.of());
mockMvc.perform(post("/user/setPassword")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(newSetPasswordDto()))
.with(csrf()))
.andExpect(status().isOk())
.andExpect(jsonPath("$.success").value(true));
verify(userService).setInitialPassword(testUser, "NewValidPass1!");
}
@Test
@DisplayName("POST /user/setPassword - rejected 401 when the StepUpService denies step-up")
void setPassword_stepUpService_deniesReturns401() throws Exception {
mockMvc = updatePasswordMockMvc();
when(userService.findUserByEmail(testUser.getEmail())).thenReturn(testUser);
when(userService.hasPassword(testUser)).thenReturn(false);
StepUpService stepUp = mock(StepUpService.class);
when(stepUp.isStepUpSatisfied(eq(testUser), eq("set-password"), any())).thenReturn(false);
ReflectionTestUtils.setField(userAPI, "stepUpServiceProvider", stepUpProvider(stepUp));
when(messageSource.getMessage(eq("message.set-password.step-up-required"), any(), any(), any(Locale.class)))
.thenReturn("Additional verification is required to set a password.");
mockMvc.perform(post("/user/setPassword")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(newSetPasswordDto()))
.with(csrf()))
.andExpect(status().isUnauthorized())
.andExpect(jsonPath("$.success").value(false))
// Distinct code from the disabled-by-default (403) branch.
.andExpect(jsonPath("$.code").value(6));
verify(userService, never()).setInitialPassword(any(), any());
}
@Test
@DisplayName("POST /user/setPassword - proceeds when the StepUpService grants step-up")
void setPassword_stepUpService_grantsProceeds() throws Exception {
mockMvc = updatePasswordMockMvc();
when(userService.findUserByEmail(testUser.getEmail())).thenReturn(testUser);
when(userService.hasPassword(testUser)).thenReturn(false);
StepUpService stepUp = mock(StepUpService.class);
when(stepUp.isStepUpSatisfied(eq(testUser), eq("set-password"), any())).thenReturn(true);
ReflectionTestUtils.setField(userAPI, "stepUpServiceProvider", stepUpProvider(stepUp));
when(passwordPolicyService.validate(eq(testUser), eq("NewValidPass1!"), eq(testUser.getEmail()), any(Locale.class)))
.thenReturn(List.of());
mockMvc.perform(post("/user/setPassword")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(newSetPasswordDto()))
.with(csrf()))
.andExpect(status().isOk())
.andExpect(jsonPath("$.success").value(true));
verify(userService).setInitialPassword(testUser, "NewValidPass1!");
}
}
@Nested
@DisplayName("SUF-02: setPassword disabled-by-default startup warning")
class SetPasswordStartupWarning {
private ListAppender<ILoggingEvent> appender;
private Logger apiLogger;
@SuppressWarnings("unchecked")
private ObjectProvider<StepUpService> providerOf(StepUpService service) {
ObjectProvider<StepUpService> provider = mock(ObjectProvider.class);
when(provider.getIfAvailable()).thenReturn(service);
return provider;
}
@BeforeEach
void attachAppender() {
apiLogger = (Logger) LoggerFactory.getLogger(UserAPI.class);
appender = new ListAppender<>();
appender.start();
apiLogger.addAppender(appender);
}
@AfterEach
void detachAppender() {
apiLogger.detachAppender(appender);
}
private long disabledWarnings() {
// UserAPI's logger is a JVM-global singleton, and this suite runs tests in parallel (see
// junit-platform.properties). warnIfInitialPasswordSetDisabled() is a @PostConstruct hook, so every other
// test that boots a Spring context (flag false, no StepUpService) fires this same WARN on its own thread
// into this shared appender. Count only warnings emitted on the current test thread — this test invokes
// the method synchronously — so a concurrently-booting context cannot pollute the count. Snapshot the list
// first (List.copyOf) to avoid a ConcurrentModificationException from a concurrent append during iteration.
String testThread = Thread.currentThread().getName();
return List.copyOf(appender.list).stream()
.filter(event -> event.getLevel() == Level.WARN)
.filter(event -> testThread.equals(event.getThreadName()))
.filter(event -> event.getFormattedMessage().contains("/user/setPassword is disabled by default"))
.count();
}
@Test
@DisplayName("warns at startup when no StepUpService bean and the opt-in flag is false")
void warnsWhenDisabledByDefault() {
ReflectionTestUtils.setField(userAPI, "stepUpServiceProvider", providerOf(null));
ReflectionTestUtils.setField(userAPI, "allowInitialPasswordSetWithoutStepUp", false);
userAPI.warnIfInitialPasswordSetDisabled();
assertThat(disabledWarnings()).isEqualTo(1);
}
@Test
@DisplayName("does not warn when a StepUpService bean is present")
void doesNotWarnWhenStepUpServicePresent() {
ReflectionTestUtils.setField(userAPI, "stepUpServiceProvider", providerOf(mock(StepUpService.class)));
ReflectionTestUtils.setField(userAPI, "allowInitialPasswordSetWithoutStepUp", false);
userAPI.warnIfInitialPasswordSetDisabled();
assertThat(disabledWarnings()).isZero();
}
@Test
@DisplayName("does not warn when the opt-in flag is enabled")
void doesNotWarnWhenFlagEnabled() {
ReflectionTestUtils.setField(userAPI, "stepUpServiceProvider", providerOf(null));
ReflectionTestUtils.setField(userAPI, "allowInitialPasswordSetWithoutStepUp", true);
userAPI.warnIfInitialPasswordSetDisabled();
assertThat(disabledWarnings()).isZero();
}
}
@Nested
@DisplayName("User Profile Tests")
class UserProfileTests {
@Test
@DisplayName("POST /user/updateUser - success")
void updateUser_success() throws Exception {
// Given
UserProfileUpdateDto updateDto = new UserProfileUpdateDto();
updateDto.setFirstName("UpdatedFirst");
updateDto.setLastName("UpdatedLast");
// Mock the principal resolver to return our test user
mockMvc = MockMvcBuilders.standaloneSetup(userAPI)
.setCustomArgumentResolvers(new HandlerMethodArgumentResolver() {
@Override
public boolean supportsParameter(org.springframework.core.MethodParameter parameter) {
return parameter.getParameterType().equals(DSUserDetails.class);
}
@Override
public Object resolveArgument(org.springframework.core.MethodParameter parameter,
org.springframework.web.method.support.ModelAndViewContainer mavContainer,
org.springframework.web.context.request.NativeWebRequest webRequest,
org.springframework.web.bind.support.WebDataBinderFactory binderFactory) {
return testUserDetails;
}
})
.setControllerAdvice(new TestExceptionHandler())
.build();
when(userService.findUserByEmail(testUser.getEmail())).thenReturn(testUser);
when(messageSource.getMessage(eq("message.update-user.success"), any(), any(), any(Locale.class)))
.thenReturn("Profile updated successfully");
when(userService.saveRegisteredUser(any(User.class))).thenReturn(testUser);
// When & Then
mockMvc.perform(post("/user/updateUser")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(updateDto))
.with(csrf()))
.andExpect(status().isOk())
.andExpect(jsonPath("$.success").value(true))
.andExpect(jsonPath("$.messages[0]").value("Profile updated successfully"));
verify(userService).saveRegisteredUser(argThat(user ->
user.getFirstName().equals("UpdatedFirst") &&
user.getLastName().equals("UpdatedLast")
));
}
@Test
@DisplayName("POST /user/updateUser - not authenticated")
void updateUser_notAuthenticated() throws Exception {
// Given
UserProfileUpdateDto updateDto = new UserProfileUpdateDto();
updateDto.setFirstName("UpdatedFirst");
updateDto.setLastName("UpdatedLast");
// When & Then
mockMvc.perform(post("/user/updateUser")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(updateDto))
.with(csrf()))
.andExpect(status().isOk())
.andExpect(jsonPath("$.success").value(false))
.andExpect(jsonPath("$.code").value(401))
.andExpect(jsonPath("$.messages[0]").value("User not logged in."));
}
@Test
@DisplayName("POST /user/updateUser - validation fails with blank firstName")
void updateUser_blankFirstName_fails() throws Exception {
// Given
UserProfileUpdateDto updateDto = new UserProfileUpdateDto();
updateDto.setFirstName(""); // Blank - should fail validation
updateDto.setLastName("UpdatedLast");
// Create a validator for the standalone setup
LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
validator.afterPropertiesSet();
// Mock the principal resolver to return our test user
mockMvc = MockMvcBuilders.standaloneSetup(userAPI)
.setValidator(validator)
.setCustomArgumentResolvers(new HandlerMethodArgumentResolver() {
@Override
public boolean supportsParameter(org.springframework.core.MethodParameter parameter) {
return parameter.getParameterType().equals(DSUserDetails.class);
}
@Override
public Object resolveArgument(org.springframework.core.MethodParameter parameter,
org.springframework.web.method.support.ModelAndViewContainer mavContainer,
org.springframework.web.context.request.NativeWebRequest webRequest,
org.springframework.web.bind.support.WebDataBinderFactory binderFactory) {
return testUserDetails;
}
})
.setControllerAdvice(new TestExceptionHandler())
.build();
// When & Then - validation should fail
mockMvc.perform(post("/user/updateUser")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(updateDto))
.with(csrf()))
.andExpect(status().isBadRequest());
verify(userService, never()).saveRegisteredUser(any(User.class));
}
@Test
@DisplayName("POST /user/updateUser - validation fails with blank lastName")
void updateUser_blankLastName_fails() throws Exception {
// Given
UserProfileUpdateDto updateDto = new UserProfileUpdateDto();
updateDto.setFirstName("UpdatedFirst");
updateDto.setLastName(""); // Blank - should fail validation
// Create a validator for the standalone setup
LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
validator.afterPropertiesSet();
// Mock the principal resolver to return our test user
mockMvc = MockMvcBuilders.standaloneSetup(userAPI)
.setValidator(validator)
.setCustomArgumentResolvers(new HandlerMethodArgumentResolver() {
@Override
public boolean supportsParameter(org.springframework.core.MethodParameter parameter) {
return parameter.getParameterType().equals(DSUserDetails.class);
}
@Override
public Object resolveArgument(org.springframework.core.MethodParameter parameter,
org.springframework.web.method.support.ModelAndViewContainer mavContainer,
org.springframework.web.context.request.NativeWebRequest webRequest,
org.springframework.web.bind.support.WebDataBinderFactory binderFactory) {
return testUserDetails;
}
})
.setControllerAdvice(new TestExceptionHandler())
.build();
// When & Then - validation should fail
mockMvc.perform(post("/user/updateUser")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(updateDto))
.with(csrf()))
.andExpect(status().isBadRequest());