From bb8cda491abf852914cb1fff3313913f365acce8 Mon Sep 17 00:00:00 2001 From: Guillaume Poirier-Morency Date: Wed, 29 Nov 2023 11:19:30 -0800 Subject: [PATCH 01/20] Add reCAPTCHA and email domain validation --- docs/customization.md | 52 ++++++-- .../java/ubc/pavlab/rdp/ValidationConfig.java | 47 ++++++++ .../rdp/controllers/LoginController.java | 64 +++++++++- src/main/java/ubc/pavlab/rdp/model/User.java | 6 +- .../rdp/settings/ApplicationSettings.java | 18 ++- .../ubc/pavlab/rdp/settings/SiteSettings.java | 11 ++ .../rdp/validation/AllowedDomainStrategy.java | 12 ++ .../pavlab/rdp/validation/EmailValidator.java | 83 +++++++++++++ .../ubc/pavlab/rdp/validation/Recaptcha.java | 10 ++ .../rdp/validation/RecaptchaValidator.java | 60 ++++++++++ .../ResourceBasedAllowedDomainStrategy.java | 111 ++++++++++++++++++ .../SetBasedAllowedDomainStrategy.java | 32 +++++ src/main/resources/application.properties | 7 ++ src/main/resources/messages.properties | 21 +++- .../resources/templates/registration.html | 13 ++ .../rdp/controllers/LoginControllerTest.java | 35 +++++- .../security/EmailValidatorFactoryTest.java | 93 +++++++++++++++ .../rdp/validation/EmailValidatorTest.java | 74 ++++++++++++ .../validation/RecaptchaValidatorTest.java | 7 ++ ...dAllowedDomainStrategyIntegrationTest.java | 15 +++ .../resources/allowed-email-domains-test.txt | 2 + 21 files changed, 754 insertions(+), 19 deletions(-) create mode 100644 src/main/java/ubc/pavlab/rdp/ValidationConfig.java create mode 100644 src/main/java/ubc/pavlab/rdp/validation/AllowedDomainStrategy.java create mode 100644 src/main/java/ubc/pavlab/rdp/validation/EmailValidator.java create mode 100644 src/main/java/ubc/pavlab/rdp/validation/Recaptcha.java create mode 100644 src/main/java/ubc/pavlab/rdp/validation/RecaptchaValidator.java create mode 100644 src/main/java/ubc/pavlab/rdp/validation/ResourceBasedAllowedDomainStrategy.java create mode 100644 src/main/java/ubc/pavlab/rdp/validation/SetBasedAllowedDomainStrategy.java create mode 100644 src/test/java/ubc/pavlab/rdp/security/EmailValidatorFactoryTest.java create mode 100644 src/test/java/ubc/pavlab/rdp/validation/EmailValidatorTest.java create mode 100644 src/test/java/ubc/pavlab/rdp/validation/RecaptchaValidatorTest.java create mode 100644 src/test/java/ubc/pavlab/rdp/validation/ResourceBasedAllowedDomainStrategyIntegrationTest.java create mode 100644 src/test/resources/allowed-email-domains-test.txt diff --git a/docs/customization.md b/docs/customization.md index d8d6767f..ccd4388e 100644 --- a/docs/customization.md +++ b/docs/customization.md @@ -1,5 +1,40 @@ # Customize your instance +## Allowed email domains (new in 1.5.8) + +You may restrict the email domains that can be used for creating new accounts by specifying a file containing one line +per domain. Matches are performed in a case-insensitive manner. + +```properties +rdp.settings.allowed-email-domains-file=file:swot.txt +rdp.settings.allowed-email-domains-refresh-delay=3600 +``` + +This feature is disabled by default. + +Note that [internationalized domains](https://en.wikipedia.org/wiki/Internationalized_domain_name) are not allowed and +will be ignored from the file. + +The default refresh delay is set to one hour. To disable it, you can set `rdp.settings.allowed-email-domains-refresh-delay` +to empty. + +There's a few projects out there that curate institutional email addresses which should be generally suitable + +Refer to [JetBrains/swot](https://github.com/JetBrains/swot) for a list of institu + +## reCAPTCHA (new in 1.5.8) + +RDP supports [reCAPTCHA v2](https://www.google.com/recaptcha/about/) to mitigate the registration of spam accounts by +bots. To enable it, add the reCAPTCHA secret to your configuration. + +```properties +rdp.settings.recaptcha-secret=mysecret +``` + +This feature is disabled by default. + +## Cached data + Most of the data used by the application is retrieved remotely at startup and subsequently updated on a monthly basis. To prevent data from being loaded on startup and/or recurrently, set the following parameter in @@ -12,6 +47,8 @@ rdp.settings.cache.enabled=false You should deploy your RDP instance at least once to have initial data before setting this property and whenever you update the software. +The following sections will cover in details individual data sources that can be imported in your registry. + ## Gene information and GO terms By default, RDP will retrieve the latest gene information from NCBI, and GO terms @@ -271,19 +308,20 @@ The page lists some basic stats at the very top and provides few action buttons: ![Actions available for simple categories.](images/simple-category-actions.png) -- "Deactivate" (or "Deactivate All Terms" in the case of an ontology category): this will remove the category from the Profile and Search pages. This action is reversible, as the category can be easily re-activated. This action is recommended in cases where a category cannot be deleted because it has already been used by some users. +- "Deactivate" (or "Deactivate All Terms" in the case of an ontology category): this will remove the category from the + Profile and Search pages. This action is reversible, as the category can be easily re-activated. This action is + recommended in cases where a category cannot be deleted because it has already been used by some users. - Update from "source": Update the ontology category using the original URL (if available) - Download as OBO: Download the category as an OBO file - - The number of used terms indicate how many terms in the ontology have been associated with associated with users. In the Edit window on the Manage Profile Category page, you can add a definition/description of the category, which is used in a tooltip on the Profile Page. You can also specify if this category will be used as a filter on the Gene -Search page. While all active categories will be available on the Researcher Search page, only categories that have "Available for gene search?" checked will be displayed on the Gene Search page. +Search page. While all active categories will be available on the Researcher Search page, only categories that have " +Available for gene search?" checked will be displayed on the Gene Search page. ![Interface for editing the properties of an ontology.](images/edit-an-ontology.png) @@ -348,8 +386,6 @@ values. A warning will be displayed in the admin section if this is the case. Read more about configuring messages in [Customizing the application messages](#customizing-the-applications-messages) section of this page. - - ### Resolving external URLs By default, ontologies and terms are resolved from [OLS](https://www.ebi.ac.uk/ols/index). Reactome pathways get a @@ -402,7 +438,6 @@ settings will retrieve all the necessary files relative to the working directory #this setting relates only to gene info files. Files for all taxons will be stord under gene/ rdp.settings.cache.load-from-disk=true rdp.settings.cache.gene-files-location=file:genes/ - #file for GO ontology rdp.settings.cache.term-file=file:go.obo #file for gene GO annotation @@ -537,7 +572,8 @@ rdp.faq.questions.=A relevant question. rdp.faq.answers.=A plausible answer. ``` -The provided default file can be found in [faq.properties](https://github.com/PavlidisLab/rdp/tree/{{ config.extra.git_ref }}/src/main/resources/faq.properties). +The provided default file can be found in [faq.properties](https://github.com/PavlidisLab/rdp/tree/{{ +config.extra.git_ref }}/src/main/resources/faq.properties). ### Ordering FAQ entries diff --git a/src/main/java/ubc/pavlab/rdp/ValidationConfig.java b/src/main/java/ubc/pavlab/rdp/ValidationConfig.java new file mode 100644 index 00000000..4a91b7a8 --- /dev/null +++ b/src/main/java/ubc/pavlab/rdp/ValidationConfig.java @@ -0,0 +1,47 @@ +package ubc.pavlab.rdp; + +import lombok.extern.apachecommons.CommonsLog; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.convert.DurationUnit; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.io.Resource; +import org.springframework.web.client.RestTemplate; +import ubc.pavlab.rdp.validation.AllowedDomainStrategy; +import ubc.pavlab.rdp.validation.EmailValidator; +import ubc.pavlab.rdp.validation.RecaptchaValidator; +import ubc.pavlab.rdp.validation.ResourceBasedAllowedDomainStrategy; + +import java.io.IOException; +import java.time.Duration; +import java.time.temporal.ChronoUnit; + +/** + * This configuration provides a few {@link org.springframework.validation.Validator} beans. + */ +@CommonsLog +@Configuration +public class ValidationConfig { + + @Bean + public EmailValidator emailValidator( + @Value("${rdp.settings.allowed-email-domains-file}") Resource allowedEmailDomainsFile, + @Value("${rdp.settings.allowed-email-domains-refresh-delay}") @DurationUnit(ChronoUnit.SECONDS) Duration refreshDelay, + @Value("${rdp.settings.allow-internationalized-domain-names}") boolean allowIdn ) throws IOException { + AllowedDomainStrategy strategy; + if ( allowedEmailDomainsFile == null ) { + strategy = ( domain ) -> true; + log.info( "No allowed email domains file specified, all domains will be allowed for newly registered users." ); + } else { + log.info( "Reading allowed email domains from " + allowedEmailDomainsFile + "..." ); + strategy = new ResourceBasedAllowedDomainStrategy( allowedEmailDomainsFile, refreshDelay ); + ( (ResourceBasedAllowedDomainStrategy) strategy ).refresh(); + } + return new EmailValidator( strategy, allowIdn ); + } + + @Bean + public RecaptchaValidator recaptchaValidator( @Value("${rdp.settings.recaptcha.secret}") String secret ) { + return new RecaptchaValidator( new RestTemplate(), secret ); + } +} diff --git a/src/main/java/ubc/pavlab/rdp/controllers/LoginController.java b/src/main/java/ubc/pavlab/rdp/controllers/LoginController.java index 0e498dd8..23eb5f57 100644 --- a/src/main/java/ubc/pavlab/rdp/controllers/LoginController.java +++ b/src/main/java/ubc/pavlab/rdp/controllers/LoginController.java @@ -2,12 +2,13 @@ import lombok.extern.apachecommons.CommonsLog; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.MessageSource; import org.springframework.http.HttpStatus; import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; -import org.springframework.validation.BindingResult; +import org.springframework.validation.*; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.GetMapping; @@ -24,6 +25,8 @@ import ubc.pavlab.rdp.services.PrivacyService; import ubc.pavlab.rdp.services.UserService; import ubc.pavlab.rdp.settings.ApplicationSettings; +import ubc.pavlab.rdp.validation.EmailValidator; +import ubc.pavlab.rdp.validation.RecaptchaValidator; import javax.servlet.http.HttpServletRequest; import java.util.Locale; @@ -44,9 +47,49 @@ public class LoginController { @Autowired private ApplicationSettings applicationSettings; + @Autowired + private EmailValidator emailValidator; + + @Autowired + private RecaptchaValidator recaptchaValidator; + + @Autowired + private MessageSource messageSource; + + /** + * Wraps a {@link EmailValidator} so that it can be applied to the {@code user.email} nested path. + */ + private class UserEmailValidator implements Validator { + + @Override + public boolean supports( Class clazz ) { + return User.class.isAssignableFrom( clazz ); + } + + @Override + public void validate( Object target, Errors errors ) { + User user = (User) target; + if ( user.getEmail() != null ) { + try { + errors.pushNestedPath( "email" ); + ValidationUtils.invokeValidator( emailValidator, user.getEmail(), errors ); + } finally { + errors.popNestedPath(); + } + } + } + } + @InitBinder("user") public void configureUserDataBinder( WebDataBinder dataBinder ) { dataBinder.setAllowedFields( "email", "password", "profile.name", "profile.lastName" ); + dataBinder.addValidators( new UserEmailValidator() ); + } + + @InitBinder("recaptcha") + public void configureRecaptchaDataBinder( WebDataBinder dataBinder ) { + dataBinder.setAllowedFields( "secret" ); + dataBinder.addValidators( recaptchaValidator ); } @GetMapping("/login") @@ -87,6 +130,9 @@ public ModelAndView createNewUser( @Validated(User.ValidationUserAccount.class) // initialize a basic user profile Profile userProfile = user.getProfile(); + if ( userProfile == null ) { + userProfile = new Profile(); + } userProfile.setPrivacyLevel( privacyService.getDefaultPrivacyLevel() ); userProfile.setShared( applicationSettings.getPrivacy().isDefaultSharing() ); userProfile.setHideGenelist( false ); @@ -105,6 +151,22 @@ public ModelAndView createNewUser( @Validated(User.ValidationUserAccount.class) if ( bindingResult.hasErrors() ) { modelAndView.setStatus( HttpStatus.BAD_REQUEST ); + // indicate to the mode + boolean isDomainNotAllowed = bindingResult.getFieldErrors( "email" ).stream() + .map( FieldError::getCode ) + .anyMatch( "EmailValidator.domainNotAllowed"::equals ); + modelAndView.addObject( "domainNotAllowed", isDomainNotAllowed ); + if ( isDomainNotAllowed ) { + // this code is not set if the email is not minimally valid, so we can safely parse it + String domain = user.getEmail().split( "@", 2 )[1]; + modelAndView.addObject( "domainNotAllowedFrom", user.getEmail() ); + modelAndView.addObject( "domainNotAllowedSubject", + messageSource.getMessage( "LoginController.domainNotAllowedSubject", + new String[]{ domain }, locale ) ); + modelAndView.addObject( "domainNotAllowedBody", + messageSource.getMessage( "LoginController.domainNotAllowedBody", + new String[]{ user.getEmail(), domain, user.getProfile().getFullName() }, locale ) ); + } } else { user = userService.create( user ); userService.createVerificationTokenForUser( user, locale ); diff --git a/src/main/java/ubc/pavlab/rdp/model/User.java b/src/main/java/ubc/pavlab/rdp/model/User.java index eb1fa50b..ea6ec23c 100644 --- a/src/main/java/ubc/pavlab/rdp/model/User.java +++ b/src/main/java/ubc/pavlab/rdp/model/User.java @@ -4,17 +4,13 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonUnwrapped; -import io.swagger.v3.oas.annotations.media.Schema; -import io.swagger.v3.oas.annotations.media.SchemaProperty; import lombok.*; import lombok.extern.apachecommons.CommonsLog; import org.hibernate.annotations.CacheConcurrencyStrategy; import org.hibernate.annotations.NaturalId; -import org.hibernate.validator.constraints.Email; import org.springframework.data.annotation.CreatedDate; import org.springframework.data.annotation.LastModifiedDate; import org.springframework.data.jpa.domain.support.AuditingEntityListener; -import org.springframework.util.StringUtils; import ubc.pavlab.rdp.model.enums.PrivacyLevelType; import ubc.pavlab.rdp.model.enums.TierType; import ubc.pavlab.rdp.model.ontology.Ontology; @@ -89,7 +85,6 @@ public static Comparator getComparator() { @NaturalId @JsonProperty(access = JsonProperty.Access.WRITE_ONLY) @Column(name = "email", unique = true, nullable = false) - @Email(message = "Your email address is not valid.", groups = { ValidationUserAccount.class }) @NotNull(message = "Please provide an email address.", groups = { ValidationUserAccount.class, ValidationServiceAccount.class }) @Size(min = 1, message = "Please provide an email address.", groups = { ValidationUserAccount.class, ValidationServiceAccount.class }) private String email; @@ -144,6 +139,7 @@ public static Comparator getComparator() { private final Set passwordResetTokens = new HashSet<>(); @Valid + @NotNull @Embedded @JsonUnwrapped private Profile profile; diff --git a/src/main/java/ubc/pavlab/rdp/settings/ApplicationSettings.java b/src/main/java/ubc/pavlab/rdp/settings/ApplicationSettings.java index 630379b0..37808606 100644 --- a/src/main/java/ubc/pavlab/rdp/settings/ApplicationSettings.java +++ b/src/main/java/ubc/pavlab/rdp/settings/ApplicationSettings.java @@ -6,18 +6,17 @@ import org.springframework.context.annotation.Configuration; import org.springframework.core.io.Resource; import org.springframework.validation.annotation.Validated; -import ubc.pavlab.rdp.ontology.resolvers.OntologyResolver; import ubc.pavlab.rdp.model.GeneInfo; import ubc.pavlab.rdp.model.enums.PrivacyLevelType; import ubc.pavlab.rdp.model.enums.ResearcherCategory; import ubc.pavlab.rdp.model.enums.ResearcherPosition; import ubc.pavlab.rdp.model.enums.TierType; import ubc.pavlab.rdp.model.ontology.Ontology; +import ubc.pavlab.rdp.ontology.resolvers.OntologyResolver; import ubc.pavlab.rdp.services.GeneInfoService; import javax.validation.constraints.Max; import javax.validation.constraints.Min; -import javax.validation.constraints.NotEmpty; import javax.validation.constraints.Size; import java.net.URI; import java.time.Duration; @@ -273,4 +272,19 @@ public static class OntologySettings { * Enabled tier types. */ public EnumSet enabledTiers; + /** + * File containing allowed email domains for registering users. + *

+ * May be null, in which case any email address will be allowed. + */ + private Resource allowedEmailDomainsFile; + /** + * Refresh delay to reload the allowed email domains file, in seconds. + */ + @DurationUnit(value = ChronoUnit.SECONDS) + private Duration allowedEmailDomainsRefreshDelay; + /** + * Allow internationalized domain names. + */ + private boolean allowInternationalizedDomainNames; } diff --git a/src/main/java/ubc/pavlab/rdp/settings/SiteSettings.java b/src/main/java/ubc/pavlab/rdp/settings/SiteSettings.java index f451b832..403fafcc 100644 --- a/src/main/java/ubc/pavlab/rdp/settings/SiteSettings.java +++ b/src/main/java/ubc/pavlab/rdp/settings/SiteSettings.java @@ -47,5 +47,16 @@ public URI getHostUrl() { @NotEmpty(message = "The admin email must be specified.") private String adminEmail; + /** + * GA4 tracker. + */ private String gaTracker; + /** + * Public reCAPTCHA key. + */ + private String recaptchaToken; + /** + * Secret reCAPTCHA key. + */ + private String recaptchaSecret; } diff --git a/src/main/java/ubc/pavlab/rdp/validation/AllowedDomainStrategy.java b/src/main/java/ubc/pavlab/rdp/validation/AllowedDomainStrategy.java new file mode 100644 index 00000000..492794cd --- /dev/null +++ b/src/main/java/ubc/pavlab/rdp/validation/AllowedDomainStrategy.java @@ -0,0 +1,12 @@ +package ubc.pavlab.rdp.validation; + +/** + * Defines a strategy to determine if a domain is allowed. + * + * @author poirigui + */ +@FunctionalInterface +public interface AllowedDomainStrategy { + + boolean allows( String domain ); +} diff --git a/src/main/java/ubc/pavlab/rdp/validation/EmailValidator.java b/src/main/java/ubc/pavlab/rdp/validation/EmailValidator.java new file mode 100644 index 00000000..475ad385 --- /dev/null +++ b/src/main/java/ubc/pavlab/rdp/validation/EmailValidator.java @@ -0,0 +1,83 @@ +package ubc.pavlab.rdp.validation; + +import org.apache.commons.lang3.StringUtils; +import org.springframework.validation.Errors; +import org.springframework.validation.Validator; + +import java.net.IDN; +import java.util.Set; + +/** + * Validate an email address against a list of allowed domains. + *

+ * If no list of allowed domains is provided, any domain is allowed and only basic validation is performed. + *

+ * If enabled, this validator can accept international domain names (IDN) and verify them against the list of allowed + * domains by first converting them to Punycode using {@link IDN#toASCII(String)}. + * + * @author poirigui + */ +public class EmailValidator implements Validator { + + /** + * List of allowed domains. + */ + private final AllowedDomainStrategy allowedDomainStrategy; + + /** + * Allow international domain names. + */ + private final boolean allowIdn; + + public EmailValidator() { + this.allowedDomainStrategy = null; + this.allowIdn = false; + } + + public EmailValidator( AllowedDomainStrategy allowedDomainStrategy, boolean allowIdn ) { + this.allowedDomainStrategy = allowedDomainStrategy; + this.allowIdn = allowIdn; + } + + public EmailValidator( Set allowedDomains, boolean allowIdn ) { + this( new SetBasedAllowedDomainStrategy( allowedDomains ), allowIdn ); + } + + @Override + public boolean supports( Class clazz ) { + return String.class.isAssignableFrom( clazz ); + } + + @Override + public void validate( Object target, Errors errors ) { + String email = (String) target; + String[] parts = email.split( "@", 2 ); + if ( parts.length != 2 ) { + errors.rejectValue( null, "EmailValidator.invalidAddress" ); + return; + } + String address = parts[0]; + if ( address.isEmpty() ) { + errors.rejectValue( null, "EmailValidator.emptyUser" ); + } + String domain = parts[1]; + if ( domain.isEmpty() ) { + errors.rejectValue( null, "EmailValidator.emptyDomain" ); + return; + } + if ( allowIdn ) { + try { + domain = IDN.toASCII( domain ); + } catch ( IllegalArgumentException e ) { + errors.rejectValue( null, "EmailValidator.domainNotConformToRfc3490", new String[]{ e.getMessage() }, "" ); + return; + } + } else if ( !StringUtils.isAsciiPrintable( domain ) ) { + errors.rejectValue( null, "EmailValidator.domainContainsUnsupportedCharacters" ); + return; + } + if ( allowedDomainStrategy != null && !allowedDomainStrategy.allows( domain ) ) { + errors.rejectValue( null, "EmailValidator.domainNotAllowed" ); + } + } +} diff --git a/src/main/java/ubc/pavlab/rdp/validation/Recaptcha.java b/src/main/java/ubc/pavlab/rdp/validation/Recaptcha.java new file mode 100644 index 00000000..ad7e5a4d --- /dev/null +++ b/src/main/java/ubc/pavlab/rdp/validation/Recaptcha.java @@ -0,0 +1,10 @@ +package ubc.pavlab.rdp.validation; + +import lombok.Data; +import lombok.Value; + +@Value +public class Recaptcha { + String response; + String remoteIp; +} diff --git a/src/main/java/ubc/pavlab/rdp/validation/RecaptchaValidator.java b/src/main/java/ubc/pavlab/rdp/validation/RecaptchaValidator.java new file mode 100644 index 00000000..0152c753 --- /dev/null +++ b/src/main/java/ubc/pavlab/rdp/validation/RecaptchaValidator.java @@ -0,0 +1,60 @@ +package ubc.pavlab.rdp.validation; + +import lombok.Data; +import lombok.Value; +import org.springframework.validation.Errors; +import org.springframework.validation.Validator; +import org.springframework.web.client.RestTemplate; + +/** + * reCAPTCHA v2 implementation as a Spring validator. + * + * @author poirigui + */ +public class RecaptchaValidator implements Validator { + + private final RestTemplate restTemplate; + private final String secret; + + public RecaptchaValidator( RestTemplate restTemplate, String secret ) { + this.restTemplate = restTemplate; + this.secret = secret; + } + + @Override + public void validate( Object target, Errors errors ) { + Recaptcha recaptcha = (Recaptcha) target; + Reply reply = restTemplate.postForObject( "https://www.google.com/recaptcha/api/siteverify", + new Payload( secret, recaptcha.getResponse(), recaptcha.getRemoteIp() ), Reply.class ); + if ( reply == null ) { + errors.reject( "" ); + return; + } + if ( !reply.success ) { + errors.reject( "" ); + } + for ( String errorCode : reply.errorCodes ) { + errors.reject( errorCode ); + } + } + + @Override + public boolean supports( Class clazz ) { + return Recaptcha.class.isAssignableFrom( clazz ); + } + + @Value + private static class Payload { + String secret; + String response; + String remoteIp; + } + + @Data + private static class Reply { + private boolean success; + private String challengeTs; + private String hostname; + private String[] errorCodes; + } +} diff --git a/src/main/java/ubc/pavlab/rdp/validation/ResourceBasedAllowedDomainStrategy.java b/src/main/java/ubc/pavlab/rdp/validation/ResourceBasedAllowedDomainStrategy.java new file mode 100644 index 00000000..fecace8a --- /dev/null +++ b/src/main/java/ubc/pavlab/rdp/validation/ResourceBasedAllowedDomainStrategy.java @@ -0,0 +1,111 @@ +package ubc.pavlab.rdp.validation; + +import lombok.extern.apachecommons.CommonsLog; +import org.apache.commons.lang3.time.StopWatch; +import org.springframework.core.io.Resource; + +import java.io.BufferedReader; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStreamReader; +import java.time.Duration; +import java.util.Set; +import java.util.stream.Collectors; + +/** + * A resource-based strategy for allowing domains. + *

+ * The resource is read line-by-line, each line being a domain that will be allowed. The domains validated using a + * {@link SetBasedAllowedDomainStrategy}, so all of its rules regarding ASCII characters and case-insensitivity applies. + *

+ * The strategy accepts an optional refresh delay which it will use to determine if the resource should be reloaded. If + * the resource is backed by a {@link java.io.File}, the last modified date will also be used to prevent unnecessary + * reload. + *

+ * If the refresh fails for any reason, an error is logged and the previous list of allowed domains is used until + * another refresh is attempted. If no previous list of allowed domains exist, the exception will be raised. For this + * reason, you might want to invoke {@link #refresh()} right after creating the strategy to catch any error early otn. + * + * @author poirigui + */ +@CommonsLog +public class ResourceBasedAllowedDomainStrategy implements AllowedDomainStrategy { + + /** + * A resource where email domains are found. + */ + private final Resource allowedEmailDomainsFile; + + /** + * A refresh delay, in ms. + */ + + private final Duration refreshDelay; + + /* internal state */ + private volatile SetBasedAllowedDomainStrategy strategy; + private long lastRefresh; + + public ResourceBasedAllowedDomainStrategy( Resource allowedEmailDomainsFile, Duration refreshDelay ) { + this.allowedEmailDomainsFile = allowedEmailDomainsFile; + this.refreshDelay = refreshDelay; + } + + @Override + public boolean allows( String domain ) { + if ( strategy == null || shouldRefresh() ) { + try { + refresh(); + } catch ( Exception e ) { + if ( strategy == null ) { + throw new RuntimeException( e ); + } else { + // pretend the resource has been refreshed, otherwise it will be reattempted on every request + this.lastRefresh = System.currentTimeMillis(); + log.error( String.format( "An error occurred while refreshing the list of allowed domains from %s. The previous list will be used until the next refresh.", allowedEmailDomainsFile ), e ); + } + } + } + return strategy.allows( domain ); + } + + /** + * Refresh the list of allowed domains. + * + * @throws IOException if an error occurred while reading the resource. + */ + public synchronized void refresh() throws IOException { + StopWatch timer = StopWatch.createStarted(); + Set allowedDomains; + try ( BufferedReader ir = new BufferedReader( new InputStreamReader( allowedEmailDomainsFile.getInputStream() ) ) ) { + allowedDomains = ir.lines().collect( Collectors.toSet() ); + } + strategy = new SetBasedAllowedDomainStrategy( allowedDomains ); + lastRefresh = System.currentTimeMillis(); + log.info( String.format( "Loaded %d domains from %s in %d ms.", allowedDomains.size(), allowedEmailDomainsFile, timer.getTime() ) ); + } + + /** + * Verify if the resource should be reloaded. + */ + private boolean shouldRefresh() { + if ( refreshDelay == null ) { + return false; + } + + // check if the file is stale + if ( System.currentTimeMillis() - lastRefresh >= refreshDelay.toMillis() ) { + try { + // avoid refreshing if the file hasn't changed + return allowedEmailDomainsFile.getFile().lastModified() > lastRefresh; + } catch ( FileNotFoundException ignored ) { + // resource is not backed by a file, most likely + } catch ( IOException e ) { + log.error( String.format( "An error occurred while checking the last modified date of %s.", allowedEmailDomainsFile ), e ); + } + return true; + } + + return false; + } +} diff --git a/src/main/java/ubc/pavlab/rdp/validation/SetBasedAllowedDomainStrategy.java b/src/main/java/ubc/pavlab/rdp/validation/SetBasedAllowedDomainStrategy.java new file mode 100644 index 00000000..47a3e1ea --- /dev/null +++ b/src/main/java/ubc/pavlab/rdp/validation/SetBasedAllowedDomainStrategy.java @@ -0,0 +1,32 @@ +package ubc.pavlab.rdp.validation; + +import org.apache.commons.lang3.StringUtils; + +import java.util.Collection; +import java.util.Set; +import java.util.TreeSet; + +/** + * Simple strategy for allowing domain based on a case-insensitive set. + *

+ * The supplied set can only contain domain with ASCII-printable characters. If you want to allow IDN, store + * Punycode in the set and enable IDN in {@link EmailValidator#EmailValidator(Set, boolean)}. + */ +public class SetBasedAllowedDomainStrategy implements AllowedDomainStrategy { + + private final Set allowedDomains; + + public SetBasedAllowedDomainStrategy( Collection allowedDomains ) { + // ascii-only domains, case-insensitive + if ( allowedDomains.stream().anyMatch( d -> !StringUtils.isAsciiPrintable( d ) ) ) { + throw new IllegalArgumentException( "Allowed domains must only contain ASCII-printable characters." ); + } + this.allowedDomains = new TreeSet<>( String.CASE_INSENSITIVE_ORDER ); + this.allowedDomains.addAll( allowedDomains ); + } + + @Override + public boolean allows( String domain ) { + return allowedDomains.contains( domain ); + } +} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 4a99c2bf..dc607e59 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -73,6 +73,13 @@ server.compression.enabled=true # = Application Specific Defaults # ============================================================== +# File containing a list of allowed email domains (ignored if empty) +rdp.settings.allowed-email-domains-file= +# Refresh delay in seconds (defaults to every hour) +rdp.settings.allowed-email-domains-refresh-delay=3600 +# Allow internationalized domain names +rdp.settings.allow-internationalized-domain-names=false + # Cached gene, orthologs, annotations, etc. rdp.settings.cache.enabled=true rdp.settings.cache.load-from-disk=false diff --git a/src/main/resources/messages.properties b/src/main/resources/messages.properties index 53bd53b8..8c5abc66 100644 --- a/src/main/resources/messages.properties +++ b/src/main/resources/messages.properties @@ -45,6 +45,18 @@ AbstractUserDetailsAuthenticationProvider.expired=User account has expired. AbstractUserDetailsAuthenticationProvider.locked=User account is locked. AbstractUserDetailsAuthenticationProvider.credentialsExpired=User credentials have expired. +# when a domain is not allowed, those are used to prefill the contact email +# {0} contains the domain part +LoginController.domainNotAllowedSubject=Attempting to register with {0} as an email domain is not allowed +# {0} contains the email address, {1} contains the domain part and {2} contains the user's full name +LoginController.domainNotAllowedBody=Hello!\ + \ + I am trying to register {0} and it appears that {1} is not in your allowed list of email domains. Could you please \ + include it? \ + \ + Best,\ + {2} + AbstractSearchController.UserSearchParams.emptyQueryNotAllowed=At least one search criteria must be provided. # {0} contains the taxon id @@ -224,4 +236,11 @@ rdp.ontologies.reactome.definition=Reactome is an open-source, open access, manu # Edit this if you use a different source for orthologs rdp.cache.ortholog-source-description=The ortholog mapping is based on DIOPT version 9 \ -results, filtered for score >5, either best forward or reverse match and Rank = "high" or Rank = "moderate". \ No newline at end of file +results, filtered for score >5, either best forward or reverse match and Rank = "high" or Rank = "moderate". + +EmailValidator.invalidAddress=The email address lacks a '@' character. +EmailValidator.emptyAddress=The user cannot be empty. +EmailValidator.emptyDomain=The domain cannot be empty. +EmailValidator.domainNotConformToRfc3490=The domain is not conform to RFC3490: {0}. +EmailValidator.domainContainsUnsupportedCharacters=The domain contains characters that are not ASCII printable. +EmailValidator.domainNotAllowed=The domain is not included in the allowed set of domains. \ No newline at end of file diff --git a/src/main/resources/templates/registration.html b/src/main/resources/templates/registration.html index 27c51927..9e614a88 100644 --- a/src/main/resources/templates/registration.html +++ b/src/main/resources/templates/registration.html @@ -13,6 +13,14 @@

+
+ Yikes! It looks like your email domain is not in our list of allowed domains. If you think this is a + mistake, + + contact us + + so that we can complete your registration. +
@@ -50,6 +58,8 @@
+ + + \ No newline at end of file diff --git a/src/test/java/ubc/pavlab/rdp/controllers/LoginControllerTest.java b/src/test/java/ubc/pavlab/rdp/controllers/LoginControllerTest.java index b3093c2a..efb4f637 100644 --- a/src/test/java/ubc/pavlab/rdp/controllers/LoginControllerTest.java +++ b/src/test/java/ubc/pavlab/rdp/controllers/LoginControllerTest.java @@ -18,6 +18,7 @@ import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.TestPropertySource; import org.springframework.test.web.servlet.MockMvc; +import org.springframework.validation.Errors; import ubc.pavlab.rdp.exception.TokenDoesNotMatchEmailException; import ubc.pavlab.rdp.exception.TokenNotFoundException; import ubc.pavlab.rdp.model.Profile; @@ -28,6 +29,8 @@ import ubc.pavlab.rdp.services.UserService; import ubc.pavlab.rdp.settings.ApplicationSettings; import ubc.pavlab.rdp.settings.SiteSettings; +import ubc.pavlab.rdp.validation.EmailValidator; +import ubc.pavlab.rdp.validation.RecaptchaValidator; import java.util.Locale; @@ -35,8 +38,7 @@ import static org.hamcrest.Matchers.containsString; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; +import static org.mockito.Mockito.*; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; @@ -73,9 +75,16 @@ public class LoginControllerTest { @MockBean(name = "ontologyMessageSource") private MessageSource ontologyMessageSource; + @MockBean + private RecaptchaValidator recaptchaValidator; + + @MockBean + private EmailValidator emailValidator; + @BeforeEach public void setUp() { when( privacyService.getDefaultPrivacyLevel() ).thenReturn( PrivacyLevelType.PRIVATE ); + when( emailValidator.supports( String.class ) ).thenReturn( true ); } @Test @@ -130,6 +139,28 @@ public void register_thenReturnSuccess() throws Exception { } ); } + @Test + public void register_whenEmailDomainIsNotAccepted_thenProduceHelpfulMessage() throws Exception { + doAnswer( a -> { + a.getArgument( 1, Errors.class ).rejectValue( null, "EmailValidator.domainNotAllowed" ); + return null; + } ).when( emailValidator ).validate( eq( "bob@example.com" ), any() ); + when( emailValidator.supports( String.class ) ).thenReturn( true ); + String expectedMailto = "from=foo@example.com&subject=&body="; + mvc.perform( post( "/registration" ) + .param( "profile.name", "Bob" ) + .param( "profile.lastName", "Smith" ) + .param( "email", "bob@example.com" ) + .param( "password", "123456" ) + .param( "passwordConfirm", "123456" ) ) + .andExpect( status().isBadRequest() ) + .andExpect( model().attribute( "domainNotAllowed", true ) ) + .andExpect( model().attribute( "domainNotAllowedFrom", "bob@example.com" ) ) + .andExpect( model().attribute( "domainNotAllowedSubject", "Attempting to register with example.com as an email domain is not allowed" ) ) + .andExpect( model().attribute( "domainNotAllowedBody", "" ) ) + .andExpect( xpath( "a[href ~= 'mailto:'].href" ).string( expectedMailto ) ); + } + @Test @Disabled("I have absolutely no idea why this converter does not work anymore. See https://github.com/PavlidisLab/rdp/issues/171 for details.") public void register_whenEmailIsUsedButNotEnabled_thenResendConfirmation() throws Exception { diff --git a/src/test/java/ubc/pavlab/rdp/security/EmailValidatorFactoryTest.java b/src/test/java/ubc/pavlab/rdp/security/EmailValidatorFactoryTest.java new file mode 100644 index 00000000..eae8e109 --- /dev/null +++ b/src/test/java/ubc/pavlab/rdp/security/EmailValidatorFactoryTest.java @@ -0,0 +1,93 @@ +package ubc.pavlab.rdp.security; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Import; +import org.springframework.core.convert.ConversionService; +import org.springframework.core.io.PathResource; +import org.springframework.format.support.DefaultFormattingConversionService; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.validation.Errors; +import ubc.pavlab.rdp.ValidationConfig; +import ubc.pavlab.rdp.validation.EmailValidator; +import ubc.pavlab.rdp.validation.ResourceBasedAllowedDomainStrategy; + +import java.io.BufferedWriter; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Duration; + +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.mockito.Mockito.*; + +@RunWith(SpringRunner.class) +@TestPropertySource(properties = { + "rdp.settings.allowed-email-domains-file=classpath:allowed-email-domains-test.txt", + "rdp.settings.allowed-email-domains-refresh-delay=PT1S", + "rdp.settings.allow-internationalized-domain-names=true" +}) +public class EmailValidatorFactoryTest { + + @TestConfiguration + @Import(ValidationConfig.class) + static class EmailValidatorFactoryTestContextConfiguration { + + @Bean + public ConversionService conversionService() { + return new DefaultFormattingConversionService(); + } + } + + @Autowired + private EmailValidator emailValidator; + + @Test + public void test() throws Exception { + Errors errors = mock( Errors.class ); + emailValidator.validate( "foo@ubc.ca", errors ); + verifyNoInteractions( errors ); + } + + @Test + public void testUnrecognizedDomain() throws Exception { + Errors errors = mock( Errors.class ); + emailValidator.validate( "foo@ubc2.ca", errors ); + verify( errors ).reject( "EmailValidator.domainNotAllowed" ); + } + + @Test + public void testReloadAfterDelay() throws Exception { + Path tmpFile = Files.createTempFile( "test", null ); + + try ( BufferedWriter writer = Files.newBufferedWriter( tmpFile ) ) { + writer.write( "ubc.ca" ); + } + + EmailValidator v = new EmailValidator( new ResourceBasedAllowedDomainStrategy( new PathResource( tmpFile ), Duration.ofMillis( 100 ) ), false ); + + Errors errors = mock( Errors.class ); + v.validate( "foo@ubc.ca", errors ); + verifyNoInteractions( errors ); + + try ( BufferedWriter writer = Files.newBufferedWriter( tmpFile ) ) { + // clearing the file + } + + // no immediate change + errors = mock( Errors.class ); + v.validate( "foo@ubc.ca", errors ); + verifyNoInteractions( errors ); + + // until the refresh delay expires... + Thread.sleep( 100 ); + + errors = mock( Errors.class ); + v.validate( "foo@ubc.ca", errors ); + verify( errors ).reject( "EmailValidator.domainNotAllowed" ); + assertNotSame( v, emailValidator ); + } +} \ No newline at end of file diff --git a/src/test/java/ubc/pavlab/rdp/validation/EmailValidatorTest.java b/src/test/java/ubc/pavlab/rdp/validation/EmailValidatorTest.java new file mode 100644 index 00000000..3c22b974 --- /dev/null +++ b/src/test/java/ubc/pavlab/rdp/validation/EmailValidatorTest.java @@ -0,0 +1,74 @@ +package ubc.pavlab.rdp.validation; + +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnit; +import org.mockito.junit.MockitoRule; +import org.springframework.validation.Errors; + +import java.util.Collections; + +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; + +public class EmailValidatorTest { + + @Rule + public MockitoRule mockitoRule = MockitoJUnit.rule(); + + @Mock + private Errors e; + + private EmailValidator v; + + @Before + public void setUp() { + v = new EmailValidator(); + } + + @Test + public void validate_whenDomainIsAllowed_thenAccept() { + v.validate( "test@test.com", e ); + verifyNoInteractions( e ); + } + + @Test + public void validate_whenDomainIsNotInAllowedDomains_thenReject() { + v = new EmailValidator( Collections.singleton( "test.com" ), false ); + v.validate( "test@test2.com", e ); + verify( e ).rejectValue( null, "EmailValidator.domainNotAllowed" ); + } + + @Test + public void validate_whenIdnIsEnabledAndDomainHasUnicodeSymbols_thenAccept() { + v = new EmailValidator( (AllowedDomainStrategy) null, true ); + v.validate( "foo@Bücher.example", e ); + verifyNoInteractions( e ); + } + + @Test + public void validate_whenDomainContainsUnsupportedCharacters_thenReject() { + v.validate( "foo@Bücher.example", e ); + verify( e ).rejectValue( null, "EmailValidator.domainContainsUnsupportedCharacters" ); + } + + @Test + public void validate_whenDomainIsMissing_thenReject() { + v.validate( "test", e ); + verify( e ).rejectValue( null, "EmailValidator.invalidAddress" ); + } + + @Test + public void validate_whenDomainIsEmpty_thenReject() { + v.validate( "test@", e ); + verify( e ).rejectValue( null, "EmailValidator.emptyDomain" ); + } + + @Test + public void validate_whenAddressIsEmpty_thenReject() { + v.validate( "@test.com", e ); + verify( e ).rejectValue( null, "EmailValidator.emptyUser" ); + } +} \ No newline at end of file diff --git a/src/test/java/ubc/pavlab/rdp/validation/RecaptchaValidatorTest.java b/src/test/java/ubc/pavlab/rdp/validation/RecaptchaValidatorTest.java new file mode 100644 index 00000000..b7b4e144 --- /dev/null +++ b/src/test/java/ubc/pavlab/rdp/validation/RecaptchaValidatorTest.java @@ -0,0 +1,7 @@ +package ubc.pavlab.rdp.validation; + +import static org.junit.Assert.*; + +public class RecaptchaValidatorTest { + +} \ No newline at end of file diff --git a/src/test/java/ubc/pavlab/rdp/validation/ResourceBasedAllowedDomainStrategyIntegrationTest.java b/src/test/java/ubc/pavlab/rdp/validation/ResourceBasedAllowedDomainStrategyIntegrationTest.java new file mode 100644 index 00000000..38e9c714 --- /dev/null +++ b/src/test/java/ubc/pavlab/rdp/validation/ResourceBasedAllowedDomainStrategyIntegrationTest.java @@ -0,0 +1,15 @@ +package ubc.pavlab.rdp.validation; + +import org.junit.Test; +import org.springframework.core.io.UrlResource; + +import java.io.IOException; + +public class ResourceBasedAllowedDomainStrategyIntegrationTest { + + @Test + public void testWithJetBrainsSwot() throws IOException { + ResourceBasedAllowedDomainStrategy strategy = new ResourceBasedAllowedDomainStrategy( new UrlResource( "https://github.com/JetBrains/swot/releases/download/latest/swot.txt" ), null ); + strategy.refresh(); + } +} \ No newline at end of file diff --git a/src/test/resources/allowed-email-domains-test.txt b/src/test/resources/allowed-email-domains-test.txt new file mode 100644 index 00000000..f5f79fb3 --- /dev/null +++ b/src/test/resources/allowed-email-domains-test.txt @@ -0,0 +1,2 @@ +example.com +ubc.ca \ No newline at end of file From 738fecf63a536f20de1b5acd518226f9374c1341 Mon Sep 17 00:00:00 2001 From: Guillaume Poirier-Morency Date: Mon, 11 Dec 2023 15:50:42 -0500 Subject: [PATCH 02/20] Update docker-compose.yml file --- docker-compose.yml | 74 ++++++++++++++++++++++++---------------------- 1 file changed, 38 insertions(+), 36 deletions(-) diff --git a/docker-compose.yml b/docker-compose.yml index f79b52e8..773302f0 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,36 +1,38 @@ -mysql56: - image: mysql:5.6 - ports: - - "3306:3306" - environment: - - MYSQL_USER=springuser - - MYSQL_PASSWORD=ThePassword - - MYSQL_DATABASE=db_example - - MYSQL_RANDOM_ROOT_PASSWORD=true -mysql57: - image: mysql:5.7 - ports: - - "3306:3306" - environment: - - MYSQL_USER=springuser - - MYSQL_PASSWORD=ThePassword - - MYSQL_DATABASE=db_example - - MYSQL_RANDOM_ROOT_PASSWORD=true -mysql: - image: mysql:8.0 - ports: - - "3306:3306" - environment: - - MYSQL_USER=springuser - - MYSQL_PASSWORD=ThePassword - - MYSQL_DATABASE=db_example - - MYSQL_RANDOM_ROOT_PASSWORD=true -mariadb: - image: mariadb:10.6 - ports: - - "3306:3306" - environment: - - MARIADB_USER=springuser - - MARIADB_PASSWORD=ThePassword - - MARIADB_DATABASE=db_example - - MARIADB_RANDOM_ROOT_PASSWORD=true +version: "3.8" +services: + mysql56: + image: mysql:5.6 + ports: + - "3306:3306" + environment: + - MYSQL_USER=springuser + - MYSQL_PASSWORD=ThePassword + - MYSQL_DATABASE=db_example + - MYSQL_RANDOM_ROOT_PASSWORD=true + mysql57: + image: mysql:5.7 + ports: + - "3306:3306" + environment: + - MYSQL_USER=springuser + - MYSQL_PASSWORD=ThePassword + - MYSQL_DATABASE=db_example + - MYSQL_RANDOM_ROOT_PASSWORD=true + mysql: + image: mysql:8.0 + ports: + - "3306:3306" + environment: + - MYSQL_USER=springuser + - MYSQL_PASSWORD=ThePassword + - MYSQL_DATABASE=db_example + - MYSQL_RANDOM_ROOT_PASSWORD=true + mariadb: + image: mariadb:10.6 + ports: + - "3306:3306" + environment: + - MARIADB_USER=springuser + - MARIADB_PASSWORD=ThePassword + - MARIADB_DATABASE=db_example + - MARIADB_RANDOM_ROOT_PASSWORD=true From 86eb7da2d31db4659547485aa5ae25564e79de01 Mon Sep 17 00:00:00 2001 From: Guillaume Poirier-Morency Date: Mon, 11 Dec 2023 23:12:29 -0500 Subject: [PATCH 03/20] Finish reCAPTCHA and email validation --- docs/customization.md | 3 +- .../java/ubc/pavlab/rdp/ValidationConfig.java | 24 +++-- .../rdp/controllers/LoginController.java | 31 ++++--- .../pavlab/rdp/validation/EmailValidator.java | 6 +- .../ubc/pavlab/rdp/validation/Recaptcha.java | 5 +- .../rdp/validation/RecaptchaValidator.java | 44 ++++++--- .../ResourceBasedAllowedDomainStrategy.java | 26 +++++- .../SetBasedAllowedDomainStrategy.java | 5 + src/main/resources/application.properties | 4 + src/main/resources/messages.properties | 26 ++++-- .../resources/templates/registration.html | 20 ++-- .../rdp/controllers/LoginControllerTest.java | 16 +++- .../security/EmailValidatorFactoryTest.java | 93 ------------------- .../EmailValidatorWithContextTest.java | 53 +++++++++++ .../rdp/validation/EmailValidatorTest.java | 64 +++++++++---- .../validation/RecaptchaValidatorTest.java | 85 ++++++++++++++++- 16 files changed, 341 insertions(+), 164 deletions(-) delete mode 100644 src/test/java/ubc/pavlab/rdp/security/EmailValidatorFactoryTest.java create mode 100644 src/test/java/ubc/pavlab/rdp/security/EmailValidatorWithContextTest.java diff --git a/docs/customization.md b/docs/customization.md index ccd4388e..0dcabf0c 100644 --- a/docs/customization.md +++ b/docs/customization.md @@ -28,7 +28,8 @@ RDP supports [reCAPTCHA v2](https://www.google.com/recaptcha/about/) to mitigate bots. To enable it, add the reCAPTCHA secret to your configuration. ```properties -rdp.settings.recaptcha-secret=mysecret +rdp.site.recaptcha-token=mytoken +rdp.site.recaptcha-secret=mysecret ``` This feature is disabled by default. diff --git a/src/main/java/ubc/pavlab/rdp/ValidationConfig.java b/src/main/java/ubc/pavlab/rdp/ValidationConfig.java index 4a91b7a8..f5e46ea6 100644 --- a/src/main/java/ubc/pavlab/rdp/ValidationConfig.java +++ b/src/main/java/ubc/pavlab/rdp/ValidationConfig.java @@ -2,10 +2,12 @@ import lombok.extern.apachecommons.CommonsLog; import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.convert.DurationUnit; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.Resource; +import org.springframework.http.converter.FormHttpMessageConverter; import org.springframework.web.client.RestTemplate; import ubc.pavlab.rdp.validation.AllowedDomainStrategy; import ubc.pavlab.rdp.validation.EmailValidator; @@ -15,6 +17,7 @@ import java.io.IOException; import java.time.Duration; import java.time.temporal.ChronoUnit; +import java.util.Set; /** * This configuration provides a few {@link org.springframework.validation.Validator} beans. @@ -29,19 +32,28 @@ public EmailValidator emailValidator( @Value("${rdp.settings.allowed-email-domains-refresh-delay}") @DurationUnit(ChronoUnit.SECONDS) Duration refreshDelay, @Value("${rdp.settings.allow-internationalized-domain-names}") boolean allowIdn ) throws IOException { AllowedDomainStrategy strategy; - if ( allowedEmailDomainsFile == null ) { - strategy = ( domain ) -> true; - log.info( "No allowed email domains file specified, all domains will be allowed for newly registered users." ); - } else { + if ( allowedEmailDomainsFile != null ) { log.info( "Reading allowed email domains from " + allowedEmailDomainsFile + "..." ); strategy = new ResourceBasedAllowedDomainStrategy( allowedEmailDomainsFile, refreshDelay ); ( (ResourceBasedAllowedDomainStrategy) strategy ).refresh(); + Set allowedDomains = ( (ResourceBasedAllowedDomainStrategy) strategy ).getAllowedDomains(); + if ( allowedDomains.size() <= 5 ) { + log.info( String.format( "Email validation is configured to accept only addresses from: %s.", String.join( ", ", allowedDomains ) ) ); + } else { + log.info( String.format( "Email validation is configured to accept only addresses from a list of %d domains.", allowedDomains.size() ) ); + } + } else { + strategy = ( domain ) -> true; + log.warn( "No allowed email domains file specified, all domains will be allowed for newly registered users." ); } return new EmailValidator( strategy, allowIdn ); } @Bean - public RecaptchaValidator recaptchaValidator( @Value("${rdp.settings.recaptcha.secret}") String secret ) { - return new RecaptchaValidator( new RestTemplate(), secret ); + @ConditionalOnProperty("rdp.site.recaptcha-secret") + public RecaptchaValidator recaptchaValidator( @Value("${rdp.site.recaptcha-secret}") String secret ) { + RestTemplate rt = new RestTemplate(); + rt.getMessageConverters().add( new FormHttpMessageConverter() ); + return new RecaptchaValidator( rt, secret ); } } diff --git a/src/main/java/ubc/pavlab/rdp/controllers/LoginController.java b/src/main/java/ubc/pavlab/rdp/controllers/LoginController.java index 23eb5f57..7cb7cc22 100644 --- a/src/main/java/ubc/pavlab/rdp/controllers/LoginController.java +++ b/src/main/java/ubc/pavlab/rdp/controllers/LoginController.java @@ -11,10 +11,7 @@ import org.springframework.validation.*; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.WebDataBinder; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.InitBinder; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import ubc.pavlab.rdp.exception.TokenException; @@ -26,10 +23,13 @@ import ubc.pavlab.rdp.services.UserService; import ubc.pavlab.rdp.settings.ApplicationSettings; import ubc.pavlab.rdp.validation.EmailValidator; +import ubc.pavlab.rdp.validation.Recaptcha; import ubc.pavlab.rdp.validation.RecaptchaValidator; import javax.servlet.http.HttpServletRequest; +import java.util.List; import java.util.Locale; +import java.util.stream.Collectors; /** * Created by mjacobson on 16/01/18. @@ -50,7 +50,7 @@ public class LoginController { @Autowired private EmailValidator emailValidator; - @Autowired + @Autowired(required = false) private RecaptchaValidator recaptchaValidator; @Autowired @@ -86,12 +86,6 @@ public void configureUserDataBinder( WebDataBinder dataBinder ) { dataBinder.addValidators( new UserEmailValidator() ); } - @InitBinder("recaptcha") - public void configureRecaptchaDataBinder( WebDataBinder dataBinder ) { - dataBinder.setAllowedFields( "secret" ); - dataBinder.addValidators( recaptchaValidator ); - } - @GetMapping("/login") public ModelAndView login() { ModelAndView modelAndView = new ModelAndView( "login" ); @@ -116,9 +110,24 @@ public ModelAndView registration() { @PostMapping("/registration") public ModelAndView createNewUser( @Validated(User.ValidationUserAccount.class) User user, BindingResult bindingResult, + @RequestParam(name = "g-recaptcha-response", required = false) String recaptchaResponse, + @RequestHeader(name = "X-Forwarded-For", required = false) List clientIp, RedirectAttributes redirectAttributes, Locale locale ) { ModelAndView modelAndView = new ModelAndView( "registration" ); + + if ( recaptchaValidator != null ) { + Recaptcha recaptcha = new Recaptcha( recaptchaResponse, clientIp != null ? clientIp.iterator().next() : null ); + BindingResult recaptchaBindingResult = new BeanPropertyBindingResult( recaptcha, "recaptcha" ); + recaptchaValidator.validate( recaptcha, recaptchaBindingResult ); + if ( recaptchaBindingResult.hasErrors() ) { + modelAndView.setStatus( HttpStatus.BAD_REQUEST ); + modelAndView.addObject( "message", recaptchaBindingResult.getAllErrors().stream().map( oe -> messageSource.getMessage( oe, locale ) ).collect( Collectors.joining( "
" ) ) ); + modelAndView.addObject( "error", Boolean.TRUE ); + return modelAndView; + } + } + User existingUser = userService.findUserByEmailNoAuth( user.getEmail() ); // profile can be missing of no profile.* fields have been set diff --git a/src/main/java/ubc/pavlab/rdp/validation/EmailValidator.java b/src/main/java/ubc/pavlab/rdp/validation/EmailValidator.java index 475ad385..da5db924 100644 --- a/src/main/java/ubc/pavlab/rdp/validation/EmailValidator.java +++ b/src/main/java/ubc/pavlab/rdp/validation/EmailValidator.java @@ -69,7 +69,7 @@ public void validate( Object target, Errors errors ) { try { domain = IDN.toASCII( domain ); } catch ( IllegalArgumentException e ) { - errors.rejectValue( null, "EmailValidator.domainNotConformToRfc3490", new String[]{ e.getMessage() }, "" ); + errors.rejectValue( null, "EmailValidator.domainNotConformToRfc3490", new String[]{ e.getMessage() }, null ); return; } } else if ( !StringUtils.isAsciiPrintable( domain ) ) { @@ -77,7 +77,9 @@ public void validate( Object target, Errors errors ) { return; } if ( allowedDomainStrategy != null && !allowedDomainStrategy.allows( domain ) ) { - errors.rejectValue( null, "EmailValidator.domainNotAllowed" ); + // at this point, the domain only contains ascii-printable, so it can safely be passed back to the user in + // an error message + errors.rejectValue( null, "EmailValidator.domainNotAllowed", new String[]{ domain }, null ); } } } diff --git a/src/main/java/ubc/pavlab/rdp/validation/Recaptcha.java b/src/main/java/ubc/pavlab/rdp/validation/Recaptcha.java index ad7e5a4d..32695818 100644 --- a/src/main/java/ubc/pavlab/rdp/validation/Recaptcha.java +++ b/src/main/java/ubc/pavlab/rdp/validation/Recaptcha.java @@ -1,10 +1,13 @@ package ubc.pavlab.rdp.validation; -import lombok.Data; import lombok.Value; +import org.springframework.lang.Nullable; +import org.springframework.web.bind.annotation.ModelAttribute; +import org.springframework.web.bind.annotation.RequestParam; @Value public class Recaptcha { String response; + @Nullable String remoteIp; } diff --git a/src/main/java/ubc/pavlab/rdp/validation/RecaptchaValidator.java b/src/main/java/ubc/pavlab/rdp/validation/RecaptchaValidator.java index 0152c753..6e0feb37 100644 --- a/src/main/java/ubc/pavlab/rdp/validation/RecaptchaValidator.java +++ b/src/main/java/ubc/pavlab/rdp/validation/RecaptchaValidator.java @@ -1,7 +1,16 @@ package ubc.pavlab.rdp.validation; +import com.fasterxml.jackson.databind.PropertyNamingStrategies; +import com.fasterxml.jackson.databind.annotation.JsonNaming; import lombok.Data; -import lombok.Value; +import org.apache.commons.lang3.StringUtils; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.lang.Nullable; +import org.springframework.util.Assert; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; import org.springframework.validation.Errors; import org.springframework.validation.Validator; import org.springframework.web.client.RestTemplate; @@ -17,6 +26,9 @@ public class RecaptchaValidator implements Validator { private final String secret; public RecaptchaValidator( RestTemplate restTemplate, String secret ) { + Assert.isTrue( restTemplate.getMessageConverters().stream().anyMatch( converter -> converter.canWrite( MultiValueMap.class, MediaType.APPLICATION_FORM_URLENCODED ) ), + "The supplied RestTemplate must support writing " + MediaType.APPLICATION_FORM_URLENCODED_VALUE + " messages." ); + Assert.isTrue( StringUtils.isNotBlank( secret ), "The secret must not be empty." ); this.restTemplate = restTemplate; this.secret = secret; } @@ -24,17 +36,28 @@ public RecaptchaValidator( RestTemplate restTemplate, String secret ) { @Override public void validate( Object target, Errors errors ) { Recaptcha recaptcha = (Recaptcha) target; + HttpHeaders headers = new HttpHeaders(); + headers.setContentType( MediaType.APPLICATION_FORM_URLENCODED ); + MultiValueMap payload = new LinkedMultiValueMap<>(); + payload.add( "secret", secret ); + payload.add( "response", recaptcha.getResponse() ); + if ( recaptcha.getRemoteIp() != null ) { + payload.add( "remoteip", recaptcha.getRemoteIp() ); + } + HttpEntity> requestEntity = new HttpEntity<>( payload, headers ); Reply reply = restTemplate.postForObject( "https://www.google.com/recaptcha/api/siteverify", - new Payload( secret, recaptcha.getResponse(), recaptcha.getRemoteIp() ), Reply.class ); + requestEntity, Reply.class ); if ( reply == null ) { - errors.reject( "" ); + errors.reject( "RecaptchaValidator.empty-reply" ); return; } if ( !reply.success ) { - errors.reject( "" ); + errors.reject( "RecaptchaValidator.unsuccessful-response" ); } - for ( String errorCode : reply.errorCodes ) { - errors.reject( errorCode ); + if ( reply.errorCodes != null ) { + for ( String errorCode : reply.errorCodes ) { + errors.reject( "RecaptchaValidator." + errorCode ); + } } } @@ -43,18 +66,13 @@ public boolean supports( Class clazz ) { return Recaptcha.class.isAssignableFrom( clazz ); } - @Value - private static class Payload { - String secret; - String response; - String remoteIp; - } - @Data + @JsonNaming(PropertyNamingStrategies.KebabCaseStrategy.class) private static class Reply { private boolean success; private String challengeTs; private String hostname; + @Nullable private String[] errorCodes; } } diff --git a/src/main/java/ubc/pavlab/rdp/validation/ResourceBasedAllowedDomainStrategy.java b/src/main/java/ubc/pavlab/rdp/validation/ResourceBasedAllowedDomainStrategy.java index fecace8a..bf56ac67 100644 --- a/src/main/java/ubc/pavlab/rdp/validation/ResourceBasedAllowedDomainStrategy.java +++ b/src/main/java/ubc/pavlab/rdp/validation/ResourceBasedAllowedDomainStrategy.java @@ -9,6 +9,7 @@ import java.io.IOException; import java.io.InputStreamReader; import java.time.Duration; +import java.util.Collections; import java.util.Set; import java.util.stream.Collectors; @@ -31,6 +32,11 @@ @CommonsLog public class ResourceBasedAllowedDomainStrategy implements AllowedDomainStrategy { + /** + * Resolution to use when comparing the last modified of a file against some recorded timestamp. + */ + private final static int LAST_MODIFIED_RESOLUTION_MS = 2; + /** * A resource where email domains are found. */ @@ -85,6 +91,17 @@ public synchronized void refresh() throws IOException { log.info( String.format( "Loaded %d domains from %s in %d ms.", allowedDomains.size(), allowedEmailDomainsFile, timer.getTime() ) ); } + /** + * Obtain a set of allowed email domains. + */ + public Set getAllowedDomains() { + if ( strategy == null ) { + return Collections.emptySet(); + } else { + return strategy.getAllowedDomains(); + } + } + /** * Verify if the resource should be reloaded. */ @@ -94,10 +111,15 @@ private boolean shouldRefresh() { } // check if the file is stale + if ( System.currentTimeMillis() - lastRefresh >= refreshDelay.toMillis() ) { try { - // avoid refreshing if the file hasn't changed - return allowedEmailDomainsFile.getFile().lastModified() > lastRefresh; + long lastModified = allowedEmailDomainsFile.getFile().lastModified(); + if ( lastModified == 0L ) { + // error reading the last modified, assume it's stale + return true; + } + return lastModified + LAST_MODIFIED_RESOLUTION_MS > lastRefresh; } catch ( FileNotFoundException ignored ) { // resource is not backed by a file, most likely } catch ( IOException e ) { diff --git a/src/main/java/ubc/pavlab/rdp/validation/SetBasedAllowedDomainStrategy.java b/src/main/java/ubc/pavlab/rdp/validation/SetBasedAllowedDomainStrategy.java index 47a3e1ea..21b73271 100644 --- a/src/main/java/ubc/pavlab/rdp/validation/SetBasedAllowedDomainStrategy.java +++ b/src/main/java/ubc/pavlab/rdp/validation/SetBasedAllowedDomainStrategy.java @@ -3,6 +3,7 @@ import org.apache.commons.lang3.StringUtils; import java.util.Collection; +import java.util.Collections; import java.util.Set; import java.util.TreeSet; @@ -29,4 +30,8 @@ public SetBasedAllowedDomainStrategy( Collection allowedDomains ) { public boolean allows( String domain ) { return allowedDomains.contains( domain ); } + + public Set getAllowedDomains() { + return Collections.unmodifiableSet( allowedDomains ); + } } diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index dc607e59..5c8c63bb 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -125,6 +125,10 @@ rdp.site.theme-color=#285187 ### Google Analytics ### rdp.site.ga-tracker= +### reCAPTCHA v2 ### +#rdp.site.recaptcha-token= +#rdp.site.recaptcha-secret= + # ============================================================== # = FAQ # ============================================================== diff --git a/src/main/resources/messages.properties b/src/main/resources/messages.properties index 8c5abc66..778c2b43 100644 --- a/src/main/resources/messages.properties +++ b/src/main/resources/messages.properties @@ -49,14 +49,26 @@ AbstractUserDetailsAuthenticationProvider.credentialsExpired=User credentials ha # {0} contains the domain part LoginController.domainNotAllowedSubject=Attempting to register with {0} as an email domain is not allowed # {0} contains the email address, {1} contains the domain part and {2} contains the user's full name -LoginController.domainNotAllowedBody=Hello!\ - \ +LoginController.domainNotAllowedBody=Hello!\n\ + \n\ I am trying to register {0} and it appears that {1} is not in your allowed list of email domains. Could you please \ - include it? \ - \ - Best,\ + include it?\n\ + \n\ + Best,\n\ {2} +RecaptchaValidator.emtpy-reply=The reply from the reCAPTCHA service was empty. +RecaptchaValidator.unsuccessful-response=The reCAPTCHA was not successful. + +# those codes are defined in https://developers.google.com/recaptcha/docs/verify +RecaptchaValidator.missing-input-secret=The secret parameter is missing. +RecaptchaValidator.invalid-input-secret=The secret parameter is invalid or malformed. +RecaptchaValidator.missing-input-response=The response parameter is missing. +RecaptchaValidator.invalid-input-response=The response parameter is invalid or malformed. +RecaptchaValidator.bad-request=The request is invalid or malformed. +RecaptchaValidator.timeout-or-duplicate=The response is no longer valid: either is too old or has been used previously. + + AbstractSearchController.UserSearchParams.emptyQueryNotAllowed=At least one search criteria must be provided. # {0} contains the taxon id @@ -239,8 +251,8 @@ rdp.cache.ortholog-source-description=The ortholog mapping is based on
-
- Yikes! It looks like your email domain is not in our list of allowed domains. If you think this is a - mistake, - + - +
@@ -58,8 +57,8 @@
- + + \ No newline at end of file diff --git a/src/test/java/ubc/pavlab/rdp/controllers/LoginControllerTest.java b/src/test/java/ubc/pavlab/rdp/controllers/LoginControllerTest.java index efb4f637..29d4ec2f 100644 --- a/src/test/java/ubc/pavlab/rdp/controllers/LoginControllerTest.java +++ b/src/test/java/ubc/pavlab/rdp/controllers/LoginControllerTest.java @@ -1,5 +1,6 @@ package ubc.pavlab.rdp.controllers; +import org.hamcrest.Matchers; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; @@ -30,6 +31,7 @@ import ubc.pavlab.rdp.settings.ApplicationSettings; import ubc.pavlab.rdp.settings.SiteSettings; import ubc.pavlab.rdp.validation.EmailValidator; +import ubc.pavlab.rdp.validation.Recaptcha; import ubc.pavlab.rdp.validation.RecaptchaValidator; import java.util.Locale; @@ -120,11 +122,13 @@ public void register_thenReturnSuccess() throws Exception { .andExpect( model().attribute( "user", new User() ) ); when( userService.create( any() ) ).thenAnswer( answer -> answer.getArgument( 0, User.class ) ); mvc.perform( post( "/registration" ) + .header( "X-Forwarded-For", "127.0.0.1", "10.0.0.2" ) .param( "profile.name", "Bob" ) .param( "profile.lastName", "Smith" ) .param( "email", "bob@example.com" ) .param( "password", "123456" ) .param( "passwordConfirm", "123456" ) + .param( "g-recaptcha-response", "1234" ) .param( "id", "27" ) ) // this field is ignored .andExpect( status().is3xxRedirection() ) .andExpect( redirectedUrl( "/login" ) ); @@ -137,6 +141,12 @@ public void register_thenReturnSuccess() throws Exception { assertThat( user.isEnabled() ).isFalse(); assertThat( user.getAnonymousId() ).isNull(); } ); + ArgumentCaptor recaptchaCaptor = ArgumentCaptor.forClass( Recaptcha.class ); + verify( recaptchaValidator ).validate( recaptchaCaptor.capture(), any() ); + assertThat( recaptchaCaptor.getValue() ).satisfies( r -> { + assertThat( r.getResponse() ).isEqualTo( "1234" ); + assertThat( r.getRemoteIp() ).isEqualTo( "127.0.0.1" ); + } ); } @Test @@ -146,7 +156,7 @@ public void register_whenEmailDomainIsNotAccepted_thenProduceHelpfulMessage() th return null; } ).when( emailValidator ).validate( eq( "bob@example.com" ), any() ); when( emailValidator.supports( String.class ) ).thenReturn( true ); - String expectedMailto = "from=foo@example.com&subject=&body="; + String expectedMailto = "mailto:admin@...from=foo@example.com&subject=&body="; mvc.perform( post( "/registration" ) .param( "profile.name", "Bob" ) .param( "profile.lastName", "Smith" ) @@ -157,8 +167,8 @@ public void register_whenEmailDomainIsNotAccepted_thenProduceHelpfulMessage() th .andExpect( model().attribute( "domainNotAllowed", true ) ) .andExpect( model().attribute( "domainNotAllowedFrom", "bob@example.com" ) ) .andExpect( model().attribute( "domainNotAllowedSubject", "Attempting to register with example.com as an email domain is not allowed" ) ) - .andExpect( model().attribute( "domainNotAllowedBody", "" ) ) - .andExpect( xpath( "a[href ~= 'mailto:'].href" ).string( expectedMailto ) ); + .andExpect( model().attribute( "domainNotAllowedBody", containsString( "bob@example.com" ) ) ) + .andExpect( xpath( "//a[starts-with(@href, 'mailto:')]/@href" ).string( Matchers.startsWith( "mailto:support@example.com?from=bob@example.com&subject=Attempting" ) ) ); } @Test diff --git a/src/test/java/ubc/pavlab/rdp/security/EmailValidatorFactoryTest.java b/src/test/java/ubc/pavlab/rdp/security/EmailValidatorFactoryTest.java deleted file mode 100644 index eae8e109..00000000 --- a/src/test/java/ubc/pavlab/rdp/security/EmailValidatorFactoryTest.java +++ /dev/null @@ -1,93 +0,0 @@ -package ubc.pavlab.rdp.security; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.TestConfiguration; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Import; -import org.springframework.core.convert.ConversionService; -import org.springframework.core.io.PathResource; -import org.springframework.format.support.DefaultFormattingConversionService; -import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.validation.Errors; -import ubc.pavlab.rdp.ValidationConfig; -import ubc.pavlab.rdp.validation.EmailValidator; -import ubc.pavlab.rdp.validation.ResourceBasedAllowedDomainStrategy; - -import java.io.BufferedWriter; -import java.nio.file.Files; -import java.nio.file.Path; -import java.time.Duration; - -import static org.junit.jupiter.api.Assertions.assertNotSame; -import static org.mockito.Mockito.*; - -@RunWith(SpringRunner.class) -@TestPropertySource(properties = { - "rdp.settings.allowed-email-domains-file=classpath:allowed-email-domains-test.txt", - "rdp.settings.allowed-email-domains-refresh-delay=PT1S", - "rdp.settings.allow-internationalized-domain-names=true" -}) -public class EmailValidatorFactoryTest { - - @TestConfiguration - @Import(ValidationConfig.class) - static class EmailValidatorFactoryTestContextConfiguration { - - @Bean - public ConversionService conversionService() { - return new DefaultFormattingConversionService(); - } - } - - @Autowired - private EmailValidator emailValidator; - - @Test - public void test() throws Exception { - Errors errors = mock( Errors.class ); - emailValidator.validate( "foo@ubc.ca", errors ); - verifyNoInteractions( errors ); - } - - @Test - public void testUnrecognizedDomain() throws Exception { - Errors errors = mock( Errors.class ); - emailValidator.validate( "foo@ubc2.ca", errors ); - verify( errors ).reject( "EmailValidator.domainNotAllowed" ); - } - - @Test - public void testReloadAfterDelay() throws Exception { - Path tmpFile = Files.createTempFile( "test", null ); - - try ( BufferedWriter writer = Files.newBufferedWriter( tmpFile ) ) { - writer.write( "ubc.ca" ); - } - - EmailValidator v = new EmailValidator( new ResourceBasedAllowedDomainStrategy( new PathResource( tmpFile ), Duration.ofMillis( 100 ) ), false ); - - Errors errors = mock( Errors.class ); - v.validate( "foo@ubc.ca", errors ); - verifyNoInteractions( errors ); - - try ( BufferedWriter writer = Files.newBufferedWriter( tmpFile ) ) { - // clearing the file - } - - // no immediate change - errors = mock( Errors.class ); - v.validate( "foo@ubc.ca", errors ); - verifyNoInteractions( errors ); - - // until the refresh delay expires... - Thread.sleep( 100 ); - - errors = mock( Errors.class ); - v.validate( "foo@ubc.ca", errors ); - verify( errors ).reject( "EmailValidator.domainNotAllowed" ); - assertNotSame( v, emailValidator ); - } -} \ No newline at end of file diff --git a/src/test/java/ubc/pavlab/rdp/security/EmailValidatorWithContextTest.java b/src/test/java/ubc/pavlab/rdp/security/EmailValidatorWithContextTest.java new file mode 100644 index 00000000..1a67b71b --- /dev/null +++ b/src/test/java/ubc/pavlab/rdp/security/EmailValidatorWithContextTest.java @@ -0,0 +1,53 @@ +package ubc.pavlab.rdp.security; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Import; +import org.springframework.core.convert.ConversionService; +import org.springframework.format.support.DefaultFormattingConversionService; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.validation.Errors; +import ubc.pavlab.rdp.ValidationConfig; +import ubc.pavlab.rdp.validation.EmailValidator; + +import static org.mockito.Mockito.*; + +@ExtendWith(SpringExtension.class) +@TestPropertySource(properties = { + "rdp.settings.allowed-email-domains-file=classpath:allowed-email-domains-test.txt", + "rdp.settings.allowed-email-domains-refresh-delay=PT0.1S", + "rdp.settings.allow-internationalized-domain-names=true" +}) +public class EmailValidatorWithContextTest { + + @TestConfiguration + @Import(ValidationConfig.class) + static class EmailValidatorFactoryTestContextConfiguration { + + @Bean + public ConversionService conversionService() { + return new DefaultFormattingConversionService(); + } + } + + @Autowired + private EmailValidator emailValidator; + + @Test + public void test() { + Errors errors = mock( Errors.class ); + emailValidator.validate( "foo@ubc.ca", errors ); + verifyNoInteractions( errors ); + } + + @Test + public void testUnrecognizedDomain() { + Errors errors = mock( Errors.class ); + emailValidator.validate( "foo@ubc2.ca", errors ); + verify( errors ).rejectValue( null, "EmailValidator.domainNotAllowed", new String[]{ "ubc2.ca" }, null ); + } +} \ No newline at end of file diff --git a/src/test/java/ubc/pavlab/rdp/validation/EmailValidatorTest.java b/src/test/java/ubc/pavlab/rdp/validation/EmailValidatorTest.java index 3c22b974..81c6cb5f 100644 --- a/src/test/java/ubc/pavlab/rdp/validation/EmailValidatorTest.java +++ b/src/test/java/ubc/pavlab/rdp/validation/EmailValidatorTest.java @@ -1,31 +1,28 @@ package ubc.pavlab.rdp.validation; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.RepeatedTest; +import org.junit.jupiter.api.Test; +import org.springframework.core.io.PathResource; import org.springframework.validation.Errors; +import java.io.BufferedWriter; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Duration; import java.util.Collections; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.*; public class EmailValidatorTest { - @Rule - public MockitoRule mockitoRule = MockitoJUnit.rule(); - - @Mock - private Errors e; - private EmailValidator v; + private Errors e; - @Before + @BeforeEach public void setUp() { v = new EmailValidator(); + e = mock( Errors.class ); } @Test @@ -38,7 +35,7 @@ public void validate_whenDomainIsAllowed_thenAccept() { public void validate_whenDomainIsNotInAllowedDomains_thenReject() { v = new EmailValidator( Collections.singleton( "test.com" ), false ); v.validate( "test@test2.com", e ); - verify( e ).rejectValue( null, "EmailValidator.domainNotAllowed" ); + verify( e ).rejectValue( null, "EmailValidator.domainNotAllowed", new String[]{ "test2.com" }, null ); } @Test @@ -71,4 +68,39 @@ public void validate_whenAddressIsEmpty_thenReject() { v.validate( "@test.com", e ); verify( e ).rejectValue( null, "EmailValidator.emptyUser" ); } + + @RepeatedTest(10) + public void validate_whenDelayForRefreshingExpiresAndDomainIsRemoved_thenReject() throws Exception { + Path tmpFile = Files.createTempFile( "test", null ); + + try ( BufferedWriter writer = Files.newBufferedWriter( tmpFile ) ) { + writer.write( "ubc.ca" ); + } + + EmailValidator v = new EmailValidator( new ResourceBasedAllowedDomainStrategy( new PathResource( tmpFile ), Duration.ofMillis( 50 ) ), false ); + + Errors errors = mock( Errors.class ); + v.validate( "foo@ubc.ca", errors ); + verifyNoInteractions( errors ); + + try ( BufferedWriter writer = Files.newBufferedWriter( tmpFile ) ) { + writer.write( "ubc2.ca" ); + } + + // no immediate change + errors = mock( Errors.class ); + v.validate( "foo@ubc.ca", errors ); + verifyNoInteractions( errors ); + + // until the refresh delay expires... + Thread.sleep( 50 ); + + errors = mock( Errors.class ); + v.validate( "foo@ubc.ca", errors ); + verify( errors ).rejectValue( null, "EmailValidator.domainNotAllowed", new String[]{ "ubc.ca" }, null ); + + errors = mock( Errors.class ); + v.validate( "foo@ubc2.ca", errors ); + verifyNoInteractions( errors ); + } } \ No newline at end of file diff --git a/src/test/java/ubc/pavlab/rdp/validation/RecaptchaValidatorTest.java b/src/test/java/ubc/pavlab/rdp/validation/RecaptchaValidatorTest.java index b7b4e144..d08cda17 100644 --- a/src/test/java/ubc/pavlab/rdp/validation/RecaptchaValidatorTest.java +++ b/src/test/java/ubc/pavlab/rdp/validation/RecaptchaValidatorTest.java @@ -1,7 +1,90 @@ package ubc.pavlab.rdp.validation; -import static org.junit.Assert.*; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.PropertyNamingStrategies; +import com.fasterxml.jackson.databind.annotation.JsonNaming; +import lombok.Value; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.json.JsonTest; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.lang.Nullable; +import org.springframework.test.web.client.MockRestServiceServer; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.validation.BeanPropertyBindingResult; +import org.springframework.validation.Errors; +import org.springframework.validation.Validator; +import org.springframework.web.client.RestTemplate; +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.test.web.client.match.MockRestRequestMatchers.content; +import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; +import static org.springframework.test.web.client.response.MockRestResponseCreators.withStatus; + +@JsonTest public class RecaptchaValidatorTest { + private RestTemplate restTemplate = new RestTemplate(); + + @Autowired + private ObjectMapper objectMapper; + + @Test + public void test() throws JsonProcessingException { + MockRestServiceServer mockServer = MockRestServiceServer.createServer( restTemplate ); + MultiValueMap expectedFormData = new LinkedMultiValueMap<>(); + expectedFormData.add( "secret", "1234" ); + expectedFormData.add( "response", "I'm human." ); + expectedFormData.add( "remoteip", "127.0.0.1" ); + mockServer.expect( requestTo( "https://www.google.com/recaptcha/api/siteverify" ) ) + .andExpect( content().formData( expectedFormData ) ) + .andRespond( withStatus( HttpStatus.OK ).contentType( MediaType.APPLICATION_JSON ) + .body( objectMapper.writeValueAsString( new Reply( true, "", "localhost", null ) ) ) ); + Validator validator = new RecaptchaValidator( restTemplate, "1234" ); + Recaptcha recaptcha = new Recaptcha( "I'm human.", "127.0.0.1" ); + Errors errors = new BeanPropertyBindingResult( recaptcha, "recaptcha" ); + validator.validate( recaptcha, errors ); + assertThat( errors.hasErrors() ).withFailMessage( errors.toString() ).isFalse(); + mockServer.verify(); + } + + @Test + public void testInvalidRecaptchaResponse() throws JsonProcessingException { + MockRestServiceServer mockServer = MockRestServiceServer.createServer( restTemplate ); + MultiValueMap expectedFormData = new LinkedMultiValueMap<>(); + expectedFormData.add( "secret", "1234" ); + expectedFormData.add( "response", "I'm a robot." ); + expectedFormData.add( "remoteip", "127.0.0.1" ); + mockServer.expect( requestTo( "https://www.google.com/recaptcha/api/siteverify" ) ) + .andExpect( content().formData( expectedFormData ) ) + .andRespond( withStatus( HttpStatus.OK ).contentType( MediaType.APPLICATION_JSON ) + .body( objectMapper.writeValueAsString( new Reply( false, "", "localhost", new String[]{ + "invalid-input-secret" + } ) ) ) ); + Validator validator = new RecaptchaValidator( restTemplate, "1234" ); + Recaptcha recaptcha = new Recaptcha( "I'm a robot.", "127.0.0.1" ); + Errors errors = new BeanPropertyBindingResult( recaptcha, "recaptcha" ); + validator.validate( recaptcha, errors ); + assertThat( errors.hasErrors() ).isTrue(); + assertThat( errors.getGlobalErrors() ) + .satisfiesExactlyInAnyOrder( ( f ) -> { + assertThat( f.getCode() ).isEqualTo( "RecaptchaValidator.unsuccessful-response" ); + }, ( f ) -> { + assertThat( f.getCode() ).isEqualTo( "RecaptchaValidator.invalid-input-secret" ); + } ); + mockServer.verify(); + } + + @Value + @JsonNaming(PropertyNamingStrategies.KebabCaseStrategy.class) + private static class Reply { + boolean success; + String challengeTs; + String hostname; + @Nullable + String[] errorCodes; + } } \ No newline at end of file From f44fad69ba9d7809a542169dcbb1b63ce97f9016 Mon Sep 17 00:00:00 2001 From: Guillaume Poirier-Morency Date: Tue, 12 Dec 2023 01:30:50 -0500 Subject: [PATCH 04/20] Ignore non-ascii-printable lines from the domain file --- .../rdp/validation/ResourceBasedAllowedDomainStrategy.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/main/java/ubc/pavlab/rdp/validation/ResourceBasedAllowedDomainStrategy.java b/src/main/java/ubc/pavlab/rdp/validation/ResourceBasedAllowedDomainStrategy.java index bf56ac67..26003b8c 100644 --- a/src/main/java/ubc/pavlab/rdp/validation/ResourceBasedAllowedDomainStrategy.java +++ b/src/main/java/ubc/pavlab/rdp/validation/ResourceBasedAllowedDomainStrategy.java @@ -1,6 +1,7 @@ package ubc.pavlab.rdp.validation; import lombok.extern.apachecommons.CommonsLog; +import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.time.StopWatch; import org.springframework.core.io.Resource; @@ -84,7 +85,8 @@ public synchronized void refresh() throws IOException { StopWatch timer = StopWatch.createStarted(); Set allowedDomains; try ( BufferedReader ir = new BufferedReader( new InputStreamReader( allowedEmailDomainsFile.getInputStream() ) ) ) { - allowedDomains = ir.lines().collect( Collectors.toSet() ); + // TODO: warn for rejected lines + allowedDomains = ir.lines().filter( StringUtils::isAsciiPrintable ).collect( Collectors.toSet() ); } strategy = new SetBasedAllowedDomainStrategy( allowedDomains ); lastRefresh = System.currentTimeMillis(); From ac73a8879c2cb4203dd16227cfda0236955e481b Mon Sep 17 00:00:00 2001 From: Guillaume Poirier-Morency Date: Tue, 12 Dec 2023 01:43:42 -0500 Subject: [PATCH 05/20] Add a test for a domain that contains an invalid IDN character --- .../ubc/pavlab/rdp/validation/EmailValidatorTest.java | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/test/java/ubc/pavlab/rdp/validation/EmailValidatorTest.java b/src/test/java/ubc/pavlab/rdp/validation/EmailValidatorTest.java index 81c6cb5f..40a061c6 100644 --- a/src/test/java/ubc/pavlab/rdp/validation/EmailValidatorTest.java +++ b/src/test/java/ubc/pavlab/rdp/validation/EmailValidatorTest.java @@ -45,6 +45,14 @@ public void validate_whenIdnIsEnabledAndDomainHasUnicodeSymbols_thenAccept() { verifyNoInteractions( e ); } + @Test + public void validate_whenIdnIsEnabledAndDomainHasInvalidUnicodeSymbols_thenReject() { + v = new EmailValidator( (AllowedDomainStrategy) null, true ); + // that's the code for a chequered flag 🏁 + v.validate( "foo@B\uD83C\uDFC1cher.example", e ); + verify( e ).rejectValue( isNull(), eq( "EmailValidator.domainNotConformToRfc3490" ), any(), isNull() ); + } + @Test public void validate_whenDomainContainsUnsupportedCharacters_thenReject() { v.validate( "foo@Bücher.example", e ); From 61681c63ce3232effdf15700b8d8715ba83cedaa Mon Sep 17 00:00:00 2001 From: Guillaume Poirier-Morency Date: Tue, 12 Dec 2023 10:21:46 -0500 Subject: [PATCH 06/20] Improve assertion for ensuring that all allowed domains are ascii-printable --- .../java/ubc/pavlab/rdp/validation/RecaptchaValidator.java | 1 - .../rdp/validation/SetBasedAllowedDomainStrategy.java | 6 +++--- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/src/main/java/ubc/pavlab/rdp/validation/RecaptchaValidator.java b/src/main/java/ubc/pavlab/rdp/validation/RecaptchaValidator.java index 6e0feb37..b282fda2 100644 --- a/src/main/java/ubc/pavlab/rdp/validation/RecaptchaValidator.java +++ b/src/main/java/ubc/pavlab/rdp/validation/RecaptchaValidator.java @@ -21,7 +21,6 @@ * @author poirigui */ public class RecaptchaValidator implements Validator { - private final RestTemplate restTemplate; private final String secret; diff --git a/src/main/java/ubc/pavlab/rdp/validation/SetBasedAllowedDomainStrategy.java b/src/main/java/ubc/pavlab/rdp/validation/SetBasedAllowedDomainStrategy.java index 21b73271..2985bd66 100644 --- a/src/main/java/ubc/pavlab/rdp/validation/SetBasedAllowedDomainStrategy.java +++ b/src/main/java/ubc/pavlab/rdp/validation/SetBasedAllowedDomainStrategy.java @@ -1,6 +1,7 @@ package ubc.pavlab.rdp.validation; import org.apache.commons.lang3.StringUtils; +import org.springframework.util.Assert; import java.util.Collection; import java.util.Collections; @@ -19,9 +20,8 @@ public class SetBasedAllowedDomainStrategy implements AllowedDomainStrategy { public SetBasedAllowedDomainStrategy( Collection allowedDomains ) { // ascii-only domains, case-insensitive - if ( allowedDomains.stream().anyMatch( d -> !StringUtils.isAsciiPrintable( d ) ) ) { - throw new IllegalArgumentException( "Allowed domains must only contain ASCII-printable characters." ); - } + Assert.isTrue( allowedDomains.stream().allMatch( StringUtils::isAsciiPrintable ), + "Allowed domains must only contain ASCII-printable characters." ); this.allowedDomains = new TreeSet<>( String.CASE_INSENSITIVE_ORDER ); this.allowedDomains.addAll( allowedDomains ); } From cbeac33c3f6e17ec6d2645e9f1e8df2d53b2caaa Mon Sep 17 00:00:00 2001 From: Guillaume Poirier-Morency Date: Tue, 12 Dec 2023 12:01:06 -0500 Subject: [PATCH 07/20] Allow domains to be specified from a list in addition to a file. Use Apache FileUtils.lastModified() to check for the last modified timestamp and handle the IOException properly. Improve naming consistency for settings. --- .../java/ubc/pavlab/rdp/ValidationConfig.java | 44 +++++++++++++------ .../rdp/settings/ApplicationSettings.java | 13 ++++-- .../ResourceBasedAllowedDomainStrategy.java | 15 +++---- src/main/resources/application.properties | 4 +- .../EmailValidatorWithContextTest.java | 12 ++++- .../rdp/validation/EmailValidatorTest.java | 27 ++++++++++++ 6 files changed, 85 insertions(+), 30 deletions(-) diff --git a/src/main/java/ubc/pavlab/rdp/ValidationConfig.java b/src/main/java/ubc/pavlab/rdp/ValidationConfig.java index f5e46ea6..034cfdd1 100644 --- a/src/main/java/ubc/pavlab/rdp/ValidationConfig.java +++ b/src/main/java/ubc/pavlab/rdp/ValidationConfig.java @@ -9,14 +9,13 @@ import org.springframework.core.io.Resource; import org.springframework.http.converter.FormHttpMessageConverter; import org.springframework.web.client.RestTemplate; -import ubc.pavlab.rdp.validation.AllowedDomainStrategy; -import ubc.pavlab.rdp.validation.EmailValidator; -import ubc.pavlab.rdp.validation.RecaptchaValidator; -import ubc.pavlab.rdp.validation.ResourceBasedAllowedDomainStrategy; +import ubc.pavlab.rdp.validation.*; import java.io.IOException; import java.time.Duration; import java.time.temporal.ChronoUnit; +import java.util.ArrayList; +import java.util.List; import java.util.Set; /** @@ -28,23 +27,40 @@ public class ValidationConfig { @Bean public EmailValidator emailValidator( + @Value("${rdp.settings.allowed-email-domains}") List allowedEmailDomains, @Value("${rdp.settings.allowed-email-domains-file}") Resource allowedEmailDomainsFile, - @Value("${rdp.settings.allowed-email-domains-refresh-delay}") @DurationUnit(ChronoUnit.SECONDS) Duration refreshDelay, - @Value("${rdp.settings.allow-internationalized-domain-names}") boolean allowIdn ) throws IOException { - AllowedDomainStrategy strategy; + @Value("${rdp.settings.allowed-email-domains-file-refresh-delay}") @DurationUnit(ChronoUnit.SECONDS) Duration refreshDelay, + @Value("${rdp.settings.allow-internationalized-email-domains}") boolean allowIdn ) throws IOException { + List strategies = new ArrayList<>(); + if ( allowedEmailDomains != null && !allowedEmailDomains.isEmpty() ) { + SetBasedAllowedDomainStrategy strategy = new SetBasedAllowedDomainStrategy( allowedEmailDomains ); + strategies.add( strategy ); + log.info( String.format( "Email validation is configured to accept addresses from: %s.", String.join( ", ", + strategy.getAllowedDomains() ) ) ); + } if ( allowedEmailDomainsFile != null ) { log.info( "Reading allowed email domains from " + allowedEmailDomainsFile + "..." ); - strategy = new ResourceBasedAllowedDomainStrategy( allowedEmailDomainsFile, refreshDelay ); - ( (ResourceBasedAllowedDomainStrategy) strategy ).refresh(); - Set allowedDomains = ( (ResourceBasedAllowedDomainStrategy) strategy ).getAllowedDomains(); - if ( allowedDomains.size() <= 5 ) { - log.info( String.format( "Email validation is configured to accept only addresses from: %s.", String.join( ", ", allowedDomains ) ) ); + if ( refreshDelay.isZero() ) { + log.warn( "The refresh delay for reading " + allowedEmailDomainsFile + " is set to zero: the file will be re-read for every email domain validation." ); + } + ResourceBasedAllowedDomainStrategy strategy = new ResourceBasedAllowedDomainStrategy( allowedEmailDomainsFile, refreshDelay ); + strategy.refresh(); + Set allowedDomains = strategy.getAllowedDomains(); + strategies.add( strategy ); + if ( strategy.getAllowedDomains().size() <= 5 ) { + log.info( String.format( "Email validation is configured to accept addresses from: %s.", String.join( ", ", allowedDomains ) ) ); } else { - log.info( String.format( "Email validation is configured to accept only addresses from a list of %d domains.", allowedDomains.size() ) ); + log.info( String.format( "Email validation is configured to accept addresses from a list of %d domains.", allowedDomains.size() ) ); } - } else { + } + AllowedDomainStrategy strategy; + if ( strategies.isEmpty() ) { strategy = ( domain ) -> true; log.warn( "No allowed email domains file specified, all domains will be allowed for newly registered users." ); + } else if ( strategies.size() == 1 ) { + strategy = strategies.iterator().next(); + } else { + strategy = domain -> strategies.stream().anyMatch( s -> s.allows( domain ) ); } return new EmailValidator( strategy, allowIdn ); } diff --git a/src/main/java/ubc/pavlab/rdp/settings/ApplicationSettings.java b/src/main/java/ubc/pavlab/rdp/settings/ApplicationSettings.java index 37808606..4b2293cb 100644 --- a/src/main/java/ubc/pavlab/rdp/settings/ApplicationSettings.java +++ b/src/main/java/ubc/pavlab/rdp/settings/ApplicationSettings.java @@ -272,6 +272,12 @@ public static class OntologySettings { * Enabled tier types. */ public EnumSet enabledTiers; + /** + * List of allowed email domains for registering users. + *

+ * May be null or empty, in which case any email address will be allowed. + */ + private List allowedEmailDomains; /** * File containing allowed email domains for registering users. *

@@ -282,9 +288,10 @@ public static class OntologySettings { * Refresh delay to reload the allowed email domains file, in seconds. */ @DurationUnit(value = ChronoUnit.SECONDS) - private Duration allowedEmailDomainsRefreshDelay; + private Duration allowedEmailDomainsFileRefreshDelay; /** - * Allow internationalized domain names. + * Allow internationalized domain names. + * If set to true, Punycode can be added to {@link #allowedEmailDomains} or {@link #allowedEmailDomainsFile}. */ - private boolean allowInternationalizedDomainNames; + private boolean allowInternationalizedEmailDomains; } diff --git a/src/main/java/ubc/pavlab/rdp/validation/ResourceBasedAllowedDomainStrategy.java b/src/main/java/ubc/pavlab/rdp/validation/ResourceBasedAllowedDomainStrategy.java index 26003b8c..75f465e2 100644 --- a/src/main/java/ubc/pavlab/rdp/validation/ResourceBasedAllowedDomainStrategy.java +++ b/src/main/java/ubc/pavlab/rdp/validation/ResourceBasedAllowedDomainStrategy.java @@ -1,6 +1,7 @@ package ubc.pavlab.rdp.validation; import lombok.extern.apachecommons.CommonsLog; +import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.time.StopWatch; import org.springframework.core.io.Resource; @@ -34,7 +35,8 @@ public class ResourceBasedAllowedDomainStrategy implements AllowedDomainStrategy { /** - * Resolution to use when comparing the last modified of a file against some recorded timestamp. + * Resolution to use when comparing the last modified of a file against a recorded timestamp with + * {@link System#currentTimeMillis()}. */ private final static int LAST_MODIFIED_RESOLUTION_MS = 2; @@ -111,16 +113,10 @@ private boolean shouldRefresh() { if ( refreshDelay == null ) { return false; } - - // check if the file is stale - if ( System.currentTimeMillis() - lastRefresh >= refreshDelay.toMillis() ) { + // check if the file is stale try { - long lastModified = allowedEmailDomainsFile.getFile().lastModified(); - if ( lastModified == 0L ) { - // error reading the last modified, assume it's stale - return true; - } + long lastModified = FileUtils.lastModified( allowedEmailDomainsFile.getFile() ); return lastModified + LAST_MODIFIED_RESOLUTION_MS > lastRefresh; } catch ( FileNotFoundException ignored ) { // resource is not backed by a file, most likely @@ -129,7 +125,6 @@ private boolean shouldRefresh() { } return true; } - return false; } } diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 5c8c63bb..76f14b9d 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -73,12 +73,14 @@ server.compression.enabled=true # = Application Specific Defaults # ============================================================== +# A comma-delimited list of allowed email domains (ignored if empty) +rdp.settings.allowed-email-domains= # File containing a list of allowed email domains (ignored if empty) rdp.settings.allowed-email-domains-file= # Refresh delay in seconds (defaults to every hour) rdp.settings.allowed-email-domains-refresh-delay=3600 # Allow internationalized domain names -rdp.settings.allow-internationalized-domain-names=false +rdp.settings.allow-internationalized-domains=false # Cached gene, orthologs, annotations, etc. rdp.settings.cache.enabled=true diff --git a/src/test/java/ubc/pavlab/rdp/security/EmailValidatorWithContextTest.java b/src/test/java/ubc/pavlab/rdp/security/EmailValidatorWithContextTest.java index 1a67b71b..30fbca4c 100644 --- a/src/test/java/ubc/pavlab/rdp/security/EmailValidatorWithContextTest.java +++ b/src/test/java/ubc/pavlab/rdp/security/EmailValidatorWithContextTest.java @@ -18,9 +18,10 @@ @ExtendWith(SpringExtension.class) @TestPropertySource(properties = { + "rdp.settings.allowed-email-domains=ubc3.ca", "rdp.settings.allowed-email-domains-file=classpath:allowed-email-domains-test.txt", - "rdp.settings.allowed-email-domains-refresh-delay=PT0.1S", - "rdp.settings.allow-internationalized-domain-names=true" + "rdp.settings.allowed-email-domains-file-refresh-delay=PT0.1S", + "rdp.settings.allow-internationalized-email-domains=true" }) public class EmailValidatorWithContextTest { @@ -44,6 +45,13 @@ public void test() { verifyNoInteractions( errors ); } + @Test + public void testDomainFromList() { + Errors errors = mock( Errors.class ); + emailValidator.validate( "foo@ubc3.ca", errors ); + verifyNoInteractions( errors ); + } + @Test public void testUnrecognizedDomain() { Errors errors = mock( Errors.class ); diff --git a/src/test/java/ubc/pavlab/rdp/validation/EmailValidatorTest.java b/src/test/java/ubc/pavlab/rdp/validation/EmailValidatorTest.java index 40a061c6..1e98291c 100644 --- a/src/test/java/ubc/pavlab/rdp/validation/EmailValidatorTest.java +++ b/src/test/java/ubc/pavlab/rdp/validation/EmailValidatorTest.java @@ -111,4 +111,31 @@ public void validate_whenDelayForRefreshingExpiresAndDomainIsRemoved_thenReject( v.validate( "foo@ubc2.ca", errors ); verifyNoInteractions( errors ); } + + @Test + public void validate_whenDelayForRefreshingIsZero() throws Exception { + Path tmpFile = Files.createTempFile( "test", null ); + + try ( BufferedWriter writer = Files.newBufferedWriter( tmpFile ) ) { + writer.write( "ubc.ca" ); + } + + EmailValidator v = new EmailValidator( new ResourceBasedAllowedDomainStrategy( new PathResource( tmpFile ), Duration.ofMillis( 0 ) ), false ); + + Errors errors = mock( Errors.class ); + v.validate( "foo@ubc.ca", errors ); + verifyNoInteractions( errors ); + + try ( BufferedWriter writer = Files.newBufferedWriter( tmpFile ) ) { + writer.write( "ubc2.ca" ); + } + + errors = mock( Errors.class ); + v.validate( "foo@ubc.ca", errors ); + verify( errors ).rejectValue( null, "EmailValidator.domainNotAllowed", new String[]{ "ubc.ca" }, null ); + + errors = mock( Errors.class ); + v.validate( "foo@ubc2.ca", errors ); + verifyNoInteractions( errors ); + } } \ No newline at end of file From 0e62a4a77a882e6d02fd3ad6258e84a2cb25d091 Mon Sep 17 00:00:00 2001 From: Guillaume Poirier-Morency Date: Tue, 12 Dec 2023 12:03:57 -0500 Subject: [PATCH 08/20] Update documentation --- docs/customization.md | 37 ++++++++++++------- .../rdp/validation/RecaptchaValidator.java | 1 + src/main/resources/application.properties | 4 +- 3 files changed, 26 insertions(+), 16 deletions(-) diff --git a/docs/customization.md b/docs/customization.md index 0dcabf0c..48910b67 100644 --- a/docs/customization.md +++ b/docs/customization.md @@ -1,33 +1,42 @@ # Customize your instance -## Allowed email domains (new in 1.5.8) +This section contains instruction to customize your RDP registry. -You may restrict the email domains that can be used for creating new accounts by specifying a file containing one line -per domain. Matches are performed in a case-insensitive manner. +## Allowed email providers (new in 1.5.8) -```properties +You may restrict which email providers can be used for creating new accounts by specifying a list or a file +containing allowed domains. Matches are performed in a case-insensitive manner. Only printable ASCII characters are +allowed. + +```ini +rdp.settings.allowed-email-domains=example.com rdp.settings.allowed-email-domains-file=file:swot.txt -rdp.settings.allowed-email-domains-refresh-delay=3600 +rdp.settings.allowed-email-domains-file-refresh-delay=3600 ``` +The default refresh delay is set to one hour. Disable it by setting it to an empty value. A value of `0` will cause a +refresh on every validation. + This feature is disabled by default. -Note that [internationalized domains](https://en.wikipedia.org/wiki/Internationalized_domain_name) are not allowed and -will be ignored from the file. +### Internationalized domain names -The default refresh delay is set to one hour. To disable it, you can set `rdp.settings.allowed-email-domains-refresh-delay` -to empty. +To use [internationalized domain names](https://en.wikipedia.org/wiki/Internationalized_domain_name) in email addresses, +add their Punycode to the list or file and set the following setting: -There's a few projects out there that curate institutional email addresses which should be generally suitable +```ini +rdp.settings.allow-internationalized-email-domains=true +``` -Refer to [JetBrains/swot](https://github.com/JetBrains/swot) for a list of institu +For example, to allow users from `universität.example.com` to register, add `xn--universitt-y5a.example.com` to the +file. ## reCAPTCHA (new in 1.5.8) -RDP supports [reCAPTCHA v2](https://www.google.com/recaptcha/about/) to mitigate the registration of spam accounts by -bots. To enable it, add the reCAPTCHA secret to your configuration. +RDP supports [reCAPTCHA v2](https://www.google.com/recaptcha/about/) to mitigate the registration of accounts by bots. +To enable it, add the reCAPTCHA token and secret to your configuration. -```properties +```ini rdp.site.recaptcha-token=mytoken rdp.site.recaptcha-secret=mysecret ``` diff --git a/src/main/java/ubc/pavlab/rdp/validation/RecaptchaValidator.java b/src/main/java/ubc/pavlab/rdp/validation/RecaptchaValidator.java index b282fda2..6e0feb37 100644 --- a/src/main/java/ubc/pavlab/rdp/validation/RecaptchaValidator.java +++ b/src/main/java/ubc/pavlab/rdp/validation/RecaptchaValidator.java @@ -21,6 +21,7 @@ * @author poirigui */ public class RecaptchaValidator implements Validator { + private final RestTemplate restTemplate; private final String secret; diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 76f14b9d..5b10b5e9 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -78,9 +78,9 @@ rdp.settings.allowed-email-domains= # File containing a list of allowed email domains (ignored if empty) rdp.settings.allowed-email-domains-file= # Refresh delay in seconds (defaults to every hour) -rdp.settings.allowed-email-domains-refresh-delay=3600 +rdp.settings.allowed-email-domains-file-refresh-delay=3600 # Allow internationalized domain names -rdp.settings.allow-internationalized-domains=false +rdp.settings.allow-internationalized-email-domains=false # Cached gene, orthologs, annotations, etc. rdp.settings.cache.enabled=true From c9412e37c81e70556ac485e1fc623e4fd4378c74 Mon Sep 17 00:00:00 2001 From: Guillaume Poirier-Morency Date: Tue, 12 Dec 2023 14:20:41 -0500 Subject: [PATCH 09/20] Increase resolution to 10ms --- .../rdp/validation/ResourceBasedAllowedDomainStrategy.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/ubc/pavlab/rdp/validation/ResourceBasedAllowedDomainStrategy.java b/src/main/java/ubc/pavlab/rdp/validation/ResourceBasedAllowedDomainStrategy.java index 75f465e2..13890ad5 100644 --- a/src/main/java/ubc/pavlab/rdp/validation/ResourceBasedAllowedDomainStrategy.java +++ b/src/main/java/ubc/pavlab/rdp/validation/ResourceBasedAllowedDomainStrategy.java @@ -38,7 +38,7 @@ public class ResourceBasedAllowedDomainStrategy implements AllowedDomainStrategy * Resolution to use when comparing the last modified of a file against a recorded timestamp with * {@link System#currentTimeMillis()}. */ - private final static int LAST_MODIFIED_RESOLUTION_MS = 2; + private final static int LAST_MODIFIED_RESOLUTION_MS = 10; /** * A resource where email domains are found. From 4f36dcdc17371be0eedcd17d609216aed3430933 Mon Sep 17 00:00:00 2001 From: Guillaume Poirier-Morency Date: Tue, 12 Dec 2023 15:44:27 -0500 Subject: [PATCH 10/20] Fix encoding of body in the email template --- src/main/resources/messages.properties | 6 +++--- src/main/resources/templates/registration.html | 5 +++-- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/src/main/resources/messages.properties b/src/main/resources/messages.properties index 778c2b43..ffaf8a7d 100644 --- a/src/main/resources/messages.properties +++ b/src/main/resources/messages.properties @@ -47,12 +47,12 @@ AbstractUserDetailsAuthenticationProvider.credentialsExpired=User credentials ha # when a domain is not allowed, those are used to prefill the contact email # {0} contains the domain part -LoginController.domainNotAllowedSubject=Attempting to register with {0} as an email domain is not allowed +LoginController.domainNotAllowedSubject=Register with an email address from {0} # {0} contains the email address, {1} contains the domain part and {2} contains the user's full name LoginController.domainNotAllowedBody=Hello!\n\ \n\ - I am trying to register {0} and it appears that {1} is not in your allowed list of email domains. Could you please \ - include it?\n\ + I am trying to register with {0} and it appears that {1} is not an allowed email provider. Could you please include \ + it?\n\ \n\ Best,\n\ {2} diff --git a/src/main/resources/templates/registration.html b/src/main/resources/templates/registration.html index a62db1a3..831504e8 100644 --- a/src/main/resources/templates/registration.html +++ b/src/main/resources/templates/registration.html @@ -14,8 +14,9 @@

- Yikes! It looks like your email does not belong to an allowed provider. If you think this is a mistake, - + Yikes! It looks like your email address was not issued from an allowed provider. If you think this is a + mistake, + contact us so that we can complete your registration. From 324b74eca4a873aec95bc2abb4a7f7de30cfae28 Mon Sep 17 00:00:00 2001 From: Guillaume Poirier-Morency Date: Tue, 12 Dec 2023 15:52:29 -0500 Subject: [PATCH 11/20] Add warnings when invalid lines are encoutered in the allowed domains file --- .../ResourceBasedAllowedDomainStrategy.java | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/src/main/java/ubc/pavlab/rdp/validation/ResourceBasedAllowedDomainStrategy.java b/src/main/java/ubc/pavlab/rdp/validation/ResourceBasedAllowedDomainStrategy.java index 13890ad5..2d8eac86 100644 --- a/src/main/java/ubc/pavlab/rdp/validation/ResourceBasedAllowedDomainStrategy.java +++ b/src/main/java/ubc/pavlab/rdp/validation/ResourceBasedAllowedDomainStrategy.java @@ -12,8 +12,8 @@ import java.io.InputStreamReader; import java.time.Duration; import java.util.Collections; +import java.util.HashSet; import java.util.Set; -import java.util.stream.Collectors; /** * A resource-based strategy for allowing domains. @@ -87,8 +87,17 @@ public synchronized void refresh() throws IOException { StopWatch timer = StopWatch.createStarted(); Set allowedDomains; try ( BufferedReader ir = new BufferedReader( new InputStreamReader( allowedEmailDomainsFile.getInputStream() ) ) ) { - // TODO: warn for rejected lines - allowedDomains = ir.lines().filter( StringUtils::isAsciiPrintable ).collect( Collectors.toSet() ); + allowedDomains = new HashSet<>(); + String line; + int lineno = 0; + while ( ( line = ir.readLine() ) != null ) { + lineno++; + if ( StringUtils.isAsciiPrintable( line ) ) { + allowedDomains.add( line.trim() ); + } else { + log.warn( String.format( "Invalid characters in line %d from %s, it will be ignored.", lineno, allowedEmailDomainsFile ) ); + } + } } strategy = new SetBasedAllowedDomainStrategy( allowedDomains ); lastRefresh = System.currentTimeMillis(); From ebdc01e62151b01e3063d277a26f64f005908a9b Mon Sep 17 00:00:00 2001 From: Guillaume Poirier-Morency Date: Tue, 12 Dec 2023 15:53:27 -0500 Subject: [PATCH 12/20] Include warning logs when running tests --- src/test/resources/logback-test.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/resources/logback-test.xml b/src/test/resources/logback-test.xml index 66a08244..a8aab834 100644 --- a/src/test/resources/logback-test.xml +++ b/src/test/resources/logback-test.xml @@ -12,5 +12,5 @@ - + \ No newline at end of file From a358af7bf4245f936e2cc41931330fc78f10fecb Mon Sep 17 00:00:00 2001 From: Guillaume Poirier-Morency Date: Tue, 12 Dec 2023 15:54:58 -0500 Subject: [PATCH 13/20] Slight improvement for the email message --- src/main/resources/messages.properties | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/resources/messages.properties b/src/main/resources/messages.properties index ffaf8a7d..9e1b0df9 100644 --- a/src/main/resources/messages.properties +++ b/src/main/resources/messages.properties @@ -51,8 +51,8 @@ LoginController.domainNotAllowedSubject=Register with an email address from {0} # {0} contains the email address, {1} contains the domain part and {2} contains the user's full name LoginController.domainNotAllowedBody=Hello!\n\ \n\ - I am trying to register with {0} and it appears that {1} is not an allowed email provider. Could you please include \ - it?\n\ + I am trying to register an account with {0} and it appears that {1} is not an allowed email provider. Could you please\ + include it?\n\ \n\ Best,\n\ {2} From 751efd19f1c1cb77a4c621c2172229673572011d Mon Sep 17 00:00:00 2001 From: Guillaume Poirier-Morency Date: Tue, 12 Dec 2023 16:47:10 -0500 Subject: [PATCH 14/20] Fix LoginControllerTest --- .../java/ubc/pavlab/rdp/controllers/LoginControllerTest.java | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/test/java/ubc/pavlab/rdp/controllers/LoginControllerTest.java b/src/test/java/ubc/pavlab/rdp/controllers/LoginControllerTest.java index 29d4ec2f..9ae02ff4 100644 --- a/src/test/java/ubc/pavlab/rdp/controllers/LoginControllerTest.java +++ b/src/test/java/ubc/pavlab/rdp/controllers/LoginControllerTest.java @@ -156,7 +156,6 @@ public void register_whenEmailDomainIsNotAccepted_thenProduceHelpfulMessage() th return null; } ).when( emailValidator ).validate( eq( "bob@example.com" ), any() ); when( emailValidator.supports( String.class ) ).thenReturn( true ); - String expectedMailto = "mailto:admin@...from=foo@example.com&subject=&body="; mvc.perform( post( "/registration" ) .param( "profile.name", "Bob" ) .param( "profile.lastName", "Smith" ) @@ -166,9 +165,9 @@ public void register_whenEmailDomainIsNotAccepted_thenProduceHelpfulMessage() th .andExpect( status().isBadRequest() ) .andExpect( model().attribute( "domainNotAllowed", true ) ) .andExpect( model().attribute( "domainNotAllowedFrom", "bob@example.com" ) ) - .andExpect( model().attribute( "domainNotAllowedSubject", "Attempting to register with example.com as an email domain is not allowed" ) ) + .andExpect( model().attribute( "domainNotAllowedSubject", "Register with an email address from example.com" ) ) .andExpect( model().attribute( "domainNotAllowedBody", containsString( "bob@example.com" ) ) ) - .andExpect( xpath( "//a[starts-with(@href, 'mailto:')]/@href" ).string( Matchers.startsWith( "mailto:support@example.com?from=bob@example.com&subject=Attempting" ) ) ); + .andExpect( xpath( "//a[starts-with(@href, 'mailto:')]/@href" ).string( Matchers.startsWith( "mailto:support@example.com?from=bob@example.com&subject=Register" ) ) ); } @Test From f2873bab020b224cc77f3e0edf717104193ef9ff Mon Sep 17 00:00:00 2001 From: Guillaume Poirier-Morency Date: Tue, 12 Dec 2023 16:49:42 -0500 Subject: [PATCH 15/20] Revert "Include warning logs when running tests" This reverts commit ebdc01e62151b01e3063d277a26f64f005908a9b. --- src/test/resources/logback-test.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/resources/logback-test.xml b/src/test/resources/logback-test.xml index a8aab834..66a08244 100644 --- a/src/test/resources/logback-test.xml +++ b/src/test/resources/logback-test.xml @@ -12,5 +12,5 @@ - + \ No newline at end of file From 74c876461eb0a2a1b142eec3d07e8cc12e4ede11 Mon Sep 17 00:00:00 2001 From: Guillaume Poirier-Morency Date: Wed, 13 Dec 2023 10:36:01 -0500 Subject: [PATCH 16/20] Clarify behaviour of rdp.settings.allowed-email-domains-file-refresh-delay in the settings --- src/main/resources/application.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 5b10b5e9..c87467b7 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -77,7 +77,7 @@ server.compression.enabled=true rdp.settings.allowed-email-domains= # File containing a list of allowed email domains (ignored if empty) rdp.settings.allowed-email-domains-file= -# Refresh delay in seconds (defaults to every hour) +# Refresh delay in seconds (ignored if empty, always refresh if set to zero) rdp.settings.allowed-email-domains-file-refresh-delay=3600 # Allow internationalized domain names rdp.settings.allow-internationalized-email-domains=false From 4c7661a30d488c324eed6ee18fda9875c21417b2 Mon Sep 17 00:00:00 2001 From: Guillaume Poirier-Morency Date: Fri, 15 Dec 2023 15:10:30 -0500 Subject: [PATCH 17/20] Fix concatenation in registration message body --- src/main/resources/messages.properties | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/resources/messages.properties b/src/main/resources/messages.properties index 9e1b0df9..fea1492e 100644 --- a/src/main/resources/messages.properties +++ b/src/main/resources/messages.properties @@ -51,8 +51,8 @@ LoginController.domainNotAllowedSubject=Register with an email address from {0} # {0} contains the email address, {1} contains the domain part and {2} contains the user's full name LoginController.domainNotAllowedBody=Hello!\n\ \n\ - I am trying to register an account with {0} and it appears that {1} is not an allowed email provider. Could you please\ - include it?\n\ + I am trying to register an account with {0} and it appears that {1} is not an allowed email provider. Could you \ + please include it?\n\ \n\ Best,\n\ {2} From 5b5dc49c8bb47c1e78f248b8289a9608622f33c6 Mon Sep 17 00:00:00 2001 From: Guillaume Poirier-Morency Date: Fri, 15 Dec 2023 16:39:51 -0500 Subject: [PATCH 18/20] Minor adjustment for the warning message for invalid domains --- src/main/resources/templates/registration.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/resources/templates/registration.html b/src/main/resources/templates/registration.html index 831504e8..7c355e69 100644 --- a/src/main/resources/templates/registration.html +++ b/src/main/resources/templates/registration.html @@ -14,7 +14,7 @@
- Yikes! It looks like your email address was not issued from an allowed provider. If you think this is a + It looks like your email address does not match one of the approved email domains. If you think this is a mistake, contact us From 483739b263f44a44b8c9841e75a272db1b20bfaa Mon Sep 17 00:00:00 2001 From: Guillaume Poirier-Morency Date: Fri, 15 Dec 2023 16:43:52 -0500 Subject: [PATCH 19/20] Add required .readthedocs.yaml --- .readthedocs.yaml | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 .readthedocs.yaml diff --git a/.readthedocs.yaml b/.readthedocs.yaml new file mode 100644 index 00000000..fdf99623 --- /dev/null +++ b/.readthedocs.yaml @@ -0,0 +1,10 @@ +version: 2 +build: + os: ubuntu-22.04 + tools: + python: "3.12" +mkdocs: + configuration: mkdocs.yml +python: + install: + - requirements: docs/requirements.txt From 8f5adc6da76dacc95f27767b6c4453f99d501679 Mon Sep 17 00:00:00 2001 From: Guillaume Poirier-Morency Date: Fri, 15 Dec 2023 17:28:48 -0500 Subject: [PATCH 20/20] Add an assumption that swot.txt exists to run the test --- .../ResourceBasedAllowedDomainStrategyIntegrationTest.java | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/test/java/ubc/pavlab/rdp/validation/ResourceBasedAllowedDomainStrategyIntegrationTest.java b/src/test/java/ubc/pavlab/rdp/validation/ResourceBasedAllowedDomainStrategyIntegrationTest.java index 38e9c714..42ba171a 100644 --- a/src/test/java/ubc/pavlab/rdp/validation/ResourceBasedAllowedDomainStrategyIntegrationTest.java +++ b/src/test/java/ubc/pavlab/rdp/validation/ResourceBasedAllowedDomainStrategyIntegrationTest.java @@ -5,11 +5,15 @@ import java.io.IOException; +import static org.assertj.core.api.Assumptions.assumeThat; + public class ResourceBasedAllowedDomainStrategyIntegrationTest { @Test public void testWithJetBrainsSwot() throws IOException { - ResourceBasedAllowedDomainStrategy strategy = new ResourceBasedAllowedDomainStrategy( new UrlResource( "https://github.com/JetBrains/swot/releases/download/latest/swot.txt" ), null ); + UrlResource resource = new UrlResource( "https://github.com/JetBrains/swot/releases/download/latest/swot.txt" ); + assumeThat( resource.exists() ).isTrue(); + ResourceBasedAllowedDomainStrategy strategy = new ResourceBasedAllowedDomainStrategy( resource, null ); strategy.refresh(); } } \ No newline at end of file