Skip to content

Commit

Permalink
Fix Sonar issues
Browse files Browse the repository at this point in the history
Signed-off-by: Duane May <[email protected]>
  • Loading branch information
duanemay committed Nov 13, 2024
1 parent 9ebac66 commit d02c5dd
Show file tree
Hide file tree
Showing 7 changed files with 32 additions and 49 deletions.
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package org.cloudfoundry.identity.uaa.invitations;

import com.fasterxml.jackson.core.type.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.cloudfoundry.identity.uaa.account.PasswordConfirmationValidation;
import org.cloudfoundry.identity.uaa.authentication.UaaPrincipal;
import org.cloudfoundry.identity.uaa.authentication.manager.DynamicZoneAwareAuthenticationManager;
Expand All @@ -26,8 +27,6 @@
import org.cloudfoundry.identity.uaa.util.UaaHttpRequestUtils;
import org.cloudfoundry.identity.uaa.zone.BrandingInformation;
import org.cloudfoundry.identity.uaa.zone.IdentityZoneHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.http.HttpStatus;
Expand Down Expand Up @@ -65,25 +64,23 @@
import static org.cloudfoundry.identity.uaa.constants.OriginKeys.ORIGIN;
import static org.cloudfoundry.identity.uaa.constants.OriginKeys.SAML;
import static org.cloudfoundry.identity.uaa.constants.OriginKeys.UAA;
import static org.cloudfoundry.identity.uaa.web.UaaSavedRequestAwareAuthenticationSuccessHandler.FORM_REDIRECT_PARAMETER;
import static org.cloudfoundry.identity.uaa.util.SessionUtils.SAVED_REQUEST_SESSION_ATTRIBUTE;
import static org.cloudfoundry.identity.uaa.web.UaaSavedRequestAwareAuthenticationSuccessHandler.FORM_REDIRECT_PARAMETER;
import static org.springframework.util.StringUtils.hasText;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;

@Slf4j
@Controller
@RequestMapping("/invitations")
public class InvitationsController {

private static Logger logger = LoggerFactory.getLogger(InvitationsController.class);

private final InvitationsService invitationsService;
private final ExpiringCodeStore expiringCodeStore;
private final PasswordValidator passwordValidator;
private final IdentityProviderProvisioning identityProviderProvisioning;
private final DynamicZoneAwareAuthenticationManager zoneAwareAuthenticationManager;
private final UaaUserDatabase userDatabase;
private final String spEntityID;
private final ScimUserProvisioning userProvisioning;
private final ExternalOAuthProviderConfigurator externalOAuthProviderConfigurator;

Expand All @@ -94,7 +91,6 @@ public InvitationsController(
final IdentityProviderProvisioning identityProviderProvisioning,
final DynamicZoneAwareAuthenticationManager zoneAwareAuthenticationManager,
final UaaUserDatabase userDatabase,
final @Qualifier("samlEntityID") String spEntityID,
final ScimUserProvisioning userProvisioning,
final @Qualifier("externalOAuthProviderConfigurator") ExternalOAuthProviderConfigurator externalOAuthProviderConfigurator) {
this.invitationsService = invitationsService;
Expand All @@ -103,7 +99,6 @@ public InvitationsController(
this.identityProviderProvisioning = identityProviderProvisioning;
this.zoneAwareAuthenticationManager = zoneAwareAuthenticationManager;
this.userDatabase = userDatabase;
this.spEntityID = spEntityID;
this.userProvisioning = userProvisioning;
this.externalOAuthProviderConfigurator = externalOAuthProviderConfigurator;
}
Expand Down Expand Up @@ -137,23 +132,23 @@ public String acceptInvitePage(@RequestParam String code, Model model, HttpServl
if (isUaaUserAndVerified || isExternalUserAndAcceptedInvite) {
AcceptedInvitation accepted = invitationsService.acceptInvitation(code, "");
String redirect = "redirect:" + accepted.getRedirectUri();
logger.debug(String.format("Redirecting accepted invitation for email:%s, id:%s to URL:%s", codeData.get("email"), codeData.get("user_id"), redirect));
log.debug(String.format("Redirecting accepted invitation for email:%s, id:%s to URL:%s", codeData.get("email"), codeData.get("user_id"), redirect));
return redirect;
} else if (SAML.equals(provider.getType())) {
setRequestAttributes(request, code, user);

SamlIdentityProviderDefinition definition = ObjectUtils.castInstance(provider.getConfig(), SamlIdentityProviderDefinition.class);

String redirect = "redirect:/" + SamlRedirectUtils.getIdpRedirectUrl(definition);
logger.debug(String.format("Redirecting invitation for email:%s, id:%s single SAML IDP URL:%s", codeData.get("email"), codeData.get("user_id"), redirect));
log.debug(String.format("Redirecting invitation for email:%s, id:%s single SAML IDP URL:%s", codeData.get("email"), codeData.get("user_id"), redirect));
return redirect;
} else if (OIDC10.equals(provider.getType()) || OAUTH20.equals(provider.getType())) {
setRequestAttributes(request, code, user);

AbstractExternalOAuthIdentityProviderDefinition definition = ObjectUtils.castInstance(provider.getConfig(), AbstractExternalOAuthIdentityProviderDefinition.class);

String redirect = "redirect:" + externalOAuthProviderConfigurator.getIdpAuthenticationUrl(definition, provider.getOriginKey(), request);
logger.debug(String.format("Redirecting invitation for email:%s, id:%s OIDC IDP URL:%s", codeData.get("email"), codeData.get("user_id"), redirect));
log.debug(String.format("Redirecting invitation for email:%s, id:%s OIDC IDP URL:%s", codeData.get("email"), codeData.get("user_id"), redirect));
return redirect;
} else {
UaaPrincipal uaaPrincipal = new UaaPrincipal(codeData.get("user_id"), codeData.get("email"), codeData.get("email"), origin, null, IdentityZoneHolder.get().getId());
Expand All @@ -163,12 +158,12 @@ public String acceptInvitePage(@RequestParam String code, Model model, HttpServl
model.addAttribute("provider", provider.getType());
model.addAttribute("code", code);
model.addAttribute("email", codeData.get("email"));
logger.debug(String.format("Sending user to accept invitation page email:%s, id:%s", codeData.get("email"), codeData.get("user_id")));
log.debug(String.format("Sending user to accept invitation page email:%s, id:%s", codeData.get("email"), codeData.get("user_id")));
}
updateModelWithConsentAttributes(model);
return "invitations/accept_invite";
} catch (EmptyResultDataAccessException noProviderFound) {
logger.debug(String.format("No available invitation providers for email:%s, id:%s", codeData.get("email"), codeData.get("user_id")));
log.debug(String.format("No available invitation providers for email:%s, id:%s", codeData.get("email"), codeData.get("user_id")));
return handleUnprocessableEntity(model, response, "error_message_code", "no_suitable_idp", "invitations/accept_invite");
}
}
Expand Down Expand Up @@ -252,30 +247,30 @@ public String acceptInvitation(@RequestParam("password") String password,
final ExpiringCode expiringCode = expiringCodeStore.retrieveCode(code, IdentityZoneHolder.get().getId());

if (expiringCode == null || expiringCode.getData() == null) {
logger.debug("Failing invitation. Code not found.");
log.debug("Failing invitation. Code not found.");
SecurityContextHolder.clearContext();
return handleUnprocessableEntity(model, response, "error_message_code", "code_expired", "invitations/accept_invite");
}
Map<String, String> data = JsonUtils.readValue(expiringCode.getData(), new TypeReference<>() {
});
if (principal == null || data.get("user_id") == null || !data.get("user_id").equals(principal.getId())) {
logger.debug("Failing invitation. Code and user ID mismatch.");
log.debug("Failing invitation. Code and user ID mismatch.");
SecurityContextHolder.clearContext();
return handleUnprocessableEntity(model, response, "error_message_code", "code_expired", "invitations/accept_invite");
}

final String newCode = expiringCodeStore.generateCode(expiringCode.getData(), new Timestamp(System.currentTimeMillis() + (10 * 60 * 1000)), expiringCode.getIntent(), IdentityZoneHolder.get().getId()).getCode();
BrandingInformation zoneBranding = IdentityZoneHolder.get().getConfig().getBranding();
if (zoneBranding != null && zoneBranding.getConsent() != null && !doesUserConsent) {
return processErrorReload(newCode, model, principal.getEmail(), response, "error_message_code", "missing_consent");
return processErrorReload(newCode, model, response, "error_message_code", "missing_consent");
}
if (!validation.valid()) {
return processErrorReload(newCode, model, principal.getEmail(), response, "error_message_code", validation.getMessageCode());
return processErrorReload(newCode, model, response, "error_message_code", validation.getMessageCode());
}
try {
passwordValidator.validate(password);
} catch (InvalidPasswordException e) {
return processErrorReload(newCode, model, principal.getEmail(), response, "error_message", e.getMessagesAsOneString());
return processErrorReload(newCode, model, response, "error_message", e.getMessagesAsOneString());
}
AcceptedInvitation invitation;
try {
Expand All @@ -290,7 +285,7 @@ public String acceptInvitation(@RequestParam("password") String password,
return res;
}

private String processErrorReload(String code, Model model, String email, HttpServletResponse response, String errorCode, String error) {
private String processErrorReload(String code, Model model, HttpServletResponse response, String errorCode, String error) {
ExpiringCode expiringCode = expiringCodeStore.retrieveCode(code, IdentityZoneHolder.get().getId());
Map<String, String> codeData = JsonUtils.readValue(expiringCode.getData(), new TypeReference<>() {
});
Expand All @@ -301,7 +296,7 @@ private String processErrorReload(String code, Model model, String email, HttpSe
model.addAttribute("code", newCode);
return "redirect:accept";
} catch (EmptyResultDataAccessException noProviderFound) {
logger.debug(String.format("No available invitation providers for email:%s, id:%s", codeData.get("email"), codeData.get("user_id")));
log.debug(String.format("No available invitation providers for email:%s, id:%s", codeData.get("email"), codeData.get("user_id")));
return handleUnprocessableEntity(model, response, "error_message_code", "no_suitable_idp", "invitations/accept_invite");
}
}
Expand All @@ -321,8 +316,8 @@ public String acceptLdapInvitation(@RequestParam("enterprise_username") String u
String newCode = expiringCodeStore.generateCode(expiringCode.getData(), new Timestamp(System.currentTimeMillis() + (1000 * 60 * 10)), null, IdentityZoneHolder.get().getId()).getCode();

UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);
AuthenticationManager authenticationManager = null;
IdentityProvider ldapProvider = null;
AuthenticationManager authenticationManager;
IdentityProvider ldapProvider;
try {
ldapProvider = identityProviderProvisioning.retrieveByOrigin(OriginKeys.LDAP, IdentityZoneHolder.get().getId());
zoneAwareAuthenticationManager.getLdapAuthenticationManager(IdentityZoneHolder.get(), ldapProvider).getLdapAuthenticationManager();
Expand All @@ -331,7 +326,7 @@ public String acceptLdapInvitation(@RequestParam("enterprise_username") String u
//ldap provider was not available
return handleUnprocessableEntity(model, response, "error_message_code", "no_suitable_idp", "invitations/accept_invite");
} catch (Exception x) {
logger.error("Unable to retrieve LDAP config.", x);
log.error("Unable to retrieve LDAP config.", x);
return handleUnprocessableEntity(model, response, "error_message_code", "no_suitable_idp", "invitations/accept_invite");
}
Authentication authentication;
Expand All @@ -347,7 +342,6 @@ public String acceptLdapInvitation(@RequestParam("enterprise_username") String u
return handleUnprocessableEntity(model, response, "error_message", "invite.email_mismatch", "invitations/accept_invite");
}


if (authentication.isAuthenticated()) {
//change username from email to username
user.setUserName(((ExtendedLdapUserDetails) authentication.getPrincipal()).getUsername());
Expand All @@ -361,12 +355,11 @@ public String acceptLdapInvitation(@RequestParam("enterprise_username") String u
} catch (AuthenticationException x) {
return handleUnprocessableEntity(model, response, "error_message", x.getMessage(), "invitations/accept_invite");
} catch (Exception x) {
logger.error("Unable to authenticate against LDAP", x);
log.error("Unable to authenticate against LDAP", x);
model.addAttribute("ldap", true);
model.addAttribute("email", email);
return handleUnprocessableEntity(model, response, "error_message", "bad_credentials", "invitations/accept_invite");
}

}

private String handleUnprocessableEntity(Model model, HttpServletResponse response, String attributeKey, String attributeValue, String view) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -107,9 +107,6 @@ class InvitationsControllerTest {
@Autowired
PasswordValidator passwordValidator;

@Autowired
ClientDetailsService clientDetailsService;

@Autowired
IdentityProviderProvisioning providerProvisioning;

Expand All @@ -119,9 +116,6 @@ class InvitationsControllerTest {
@Autowired
DynamicZoneAwareAuthenticationManager zoneAwareAuthenticationManager;

@Autowired
CookieBasedCsrfTokenRepository loginCookieCsrfRepository;

@Autowired
ScimUserProvisioning scimUserProvisioning;

Expand Down Expand Up @@ -835,7 +829,6 @@ InvitationsController invitationsController(final InvitationsService invitations
providerProvisioning,
zoneAwareAuthenticationManager,
userDatabase,
"sp-entity-id",
provisioning,
externalOAuthProviderConfigurator);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ void authenticateWhenAssertionContainsValidationAddressThenItSucceeds() {
Assertion assertion = assertion();
assertion.getSubject()
.getSubjectConfirmations()
.forEach((sc) -> sc.getSubjectConfirmationData().setAddress("10.10.10.10"));
.forEach(sc -> sc.getSubjectConfirmationData().setAddress("10.10.10.10"));
response.getAssertions().add(signed(assertion));
Saml2AuthenticationToken token = token(response, verifying(registration()));
this.provider.authenticate(token);
Expand Down Expand Up @@ -466,7 +466,7 @@ void authenticateWhenDecryptionKeysAreWrongThenThrowAuthenticationException() {
TestSaml2X509Credentials.assertingPartyEncryptingCredential());
response.getEncryptedAssertions().add(encryptedAssertion);
Saml2AuthenticationToken token = token(signed(response), registration()
.decryptionX509Credentials((c) -> c.add(TestSaml2X509Credentials.assertingPartyPrivateCredential())));
.decryptionX509Credentials(c -> c.add(TestSaml2X509Credentials.assertingPartyPrivateCredential())));
assertThatExceptionOfType(Saml2AuthenticationException.class)
.isThrownBy(() -> this.provider.authenticate(token))
.satisfies(errorOf(Saml2ErrorCodes.DECRYPTION_ERROR, "Failed to decrypt EncryptedData"));
Expand All @@ -478,7 +478,7 @@ void authenticateWhenAuthenticationHasDetailsThenSucceeds() {
Assertion assertion = assertion();
assertion.getSubject()
.getSubjectConfirmations()
.forEach((sc) -> sc.getSubjectConfirmationData().setAddress("10.10.10.10"));
.forEach(sc -> sc.getSubjectConfirmationData().setAddress("10.10.10.10"));
response.getAssertions().add(signed(assertion));
Saml2AuthenticationToken token = token(response, verifying(registration()));
token.setDetails("some-details");
Expand Down Expand Up @@ -539,7 +539,6 @@ void createDefaultResponseAuthenticationConverterWhenResponseThenConverts() {
@Test
void authenticateWhenResponseAuthenticationConverterConfiguredThenUses() {
Converter<ResponseToken, Saml2Authentication> authenticationConverter = mock(Converter.class);
OpenSaml4AuthenticationProvider provider = new OpenSaml4AuthenticationProvider();
provider.setResponseAuthenticationConverter(authenticationConverter);
Response response = TestOpenSamlObjects.signedResponseWithOneAssertion();
Saml2AuthenticationToken token = token(response, verifying(registration()));
Expand All @@ -558,7 +557,7 @@ void setResponseAuthenticationConverterWhenNullThenIllegalArgument() {
@Test
void authenticateWhenResponseStatusIsNotSuccessThenFails() {
Response response = TestOpenSamlObjects
.signedResponseWithOneAssertion((r) -> r.setStatus(TestOpenSamlObjects.status(StatusCode.AUTHN_FAILED)));
.signedResponseWithOneAssertion(r -> r.setStatus(TestOpenSamlObjects.status(StatusCode.AUTHN_FAILED)));
Saml2AuthenticationToken token = token(response, verifying(registration()));
assertThatExceptionOfType(Saml2AuthenticationException.class)
.isThrownBy(() -> this.provider.authenticate(token))
Expand All @@ -568,7 +567,7 @@ void authenticateWhenResponseStatusIsNotSuccessThenFails() {
@Test
void authenticateWhenResponseStatusIsSuccessThenSucceeds() {
Response response = TestOpenSamlObjects
.signedResponseWithOneAssertion((r) -> r.setStatus(TestOpenSamlObjects.successStatus()));
.signedResponseWithOneAssertion(r -> r.setStatus(TestOpenSamlObjects.successStatus()));
Saml2AuthenticationToken token = token(response, verifying(registration()));
Authentication authentication = this.provider.authenticate(token);
assertThat(authentication.getName()).isEqualTo("[email protected]");
Expand All @@ -581,10 +580,9 @@ void setResponseValidatorWhenNullThenIllegalArgument() {

@Test
void authenticateWhenCustomResponseValidatorThenUses() {
Converter<ResponseToken, Saml2ResponseValidatorResult> validator = mock(
Converter.class);
Converter<ResponseToken, Saml2ResponseValidatorResult> validator = mock(Converter.class);
// @formatter:off
provider.setResponseValidator((responseToken) -> OpenSaml4AuthenticationProvider.createDefaultResponseValidator()
provider.setResponseValidator(responseToken -> OpenSaml4AuthenticationProvider.createDefaultResponseValidator()
.convert(responseToken)
.concat(validator.convert(responseToken))
);
Expand Down Expand Up @@ -650,8 +648,7 @@ private Response response(String destination, String issuerEntityId) {
}

private AuthnRequest request() {
AuthnRequest request = TestOpenSamlObjects.authnRequest();
return request;
return TestOpenSamlObjects.authnRequest();
}

private String serializedRequest(AuthnRequest request, Saml2MessageBinding binding) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,7 @@ public void performInviteUser(String email, boolean isVerified) {
}

@Test
void acceptInvitation_for_samlUser() throws Exception {
void acceptInvitation_for_samlUser() {
webDriver.get(baseUrl + "/logout.do");

UaaClientDetails appClient = IntegrationTestUtils.getClient(scimToken, baseUrl, "app");
Expand Down
Loading

0 comments on commit d02c5dd

Please sign in to comment.