diff --git a/Dockerfile b/Dockerfile index 8d9a1e0c6e6f..612a2442f354 100644 --- a/Dockerfile +++ b/Dockerfile @@ -48,6 +48,8 @@ RUN apt-get update \ && rm -rf /var/lib/apt/lists/* # Run necessary 'ant' deploy scripts RUN ant init_installation update_configs update_code update_webapps +# A new named volume takes the owner of the folder it is mounted on, so create the volume folders ant does not create. +RUN mkdir -p /dspace/assetstore /dspace/sitemaps # Step 3 - Start up DSpace via Runnable JAR FROM docker.io/eclipse-temurin:${JDK_VERSION} @@ -55,17 +57,20 @@ FROM docker.io/eclipse-temurin:${JDK_VERSION} # See https://github.com/DSpace/DSpace/blob/main/dspace/config/config-definition.xml # "dspace__P__dir" is setting the value of the "dspace.dir" configuration. This is our installation directory. ENV dspace__P__dir=/dspace +# Run DSpace as 'dspace', not root. UID 1100 is the same as in the 7.x image. +RUN useradd -u 1100 -m -s /bin/bash dspace # Copy the /dspace directory from 'ant_build' container to /dspace in this container -COPY --from=ant_build /dspace $dspace__P__dir +COPY --chown=dspace:dspace --from=ant_build /dspace $dspace__P__dir WORKDIR $dspace__P__dir # Need host command for "[dspace]/bin/make-handle-config" RUN apt-get update \ && apt-get install -y --no-install-recommends host \ && apt-get purge -y --auto-remove \ && rm -rf /var/lib/apt/lists/* -# Expose Tomcat port (8080) & Handle Server HTTP port (8000) -EXPOSE 8080 8000 +# Expose Tomcat port (8080) & Handle Server HTTP port (8010) +EXPOSE 8080 8010 # Give java extra memory (2GB) ENV JAVA_OPTS=-Xmx2000m +USER dspace # On startup, run DSpace Runnable JAR (uses the "dspace.dir" setting defined in "dspace__P__dir" env variable) ENTRYPOINT ["java", "-jar", "webapps/server-boot.jar"] diff --git a/Dockerfile.cli b/Dockerfile.cli index 08c3430e4f33..940bca3010bc 100644 --- a/Dockerfile.cli +++ b/Dockerfile.cli @@ -42,6 +42,8 @@ RUN apt-get update \ && rm -rf /var/lib/apt/lists/* # Run necessary 'ant' deploy scripts RUN ant init_installation update_configs update_code +# A new named volume takes the owner of the folder it is mounted on, so create the assetstore folder. +RUN mkdir -p /dspace/assetstore # Step 3 - Run jdk FROM docker.io/eclipse-temurin:${JDK_VERSION} @@ -49,8 +51,10 @@ FROM docker.io/eclipse-temurin:${JDK_VERSION} # See https://github.com/DSpace/DSpace/blob/main/dspace/config/config-definition.xml # "dspace__P__dir" is setting the value of the "dspace.dir" configuration. This is our installation directory. ENV dspace__P__dir=/dspace +# Run DSpace as 'dspace', not root. UID 1100 is the same as in the backend image. +RUN useradd -u 1100 -m -s /bin/bash dspace # Copy the /dspace directory from 'ant_build' container to /dspace in this container -COPY --from=ant_build /dspace $dspace__P__dir +COPY --chown=dspace:dspace --from=ant_build /dspace $dspace__P__dir WORKDIR $dspace__P__dir # Give java extra memory (1GB) ENV JAVA_OPTS=-Xmx1000m @@ -59,6 +63,7 @@ RUN apt-get update \ && apt-get install -y --no-install-recommends unzip \ && apt-get purge -y --auto-remove \ && rm -rf /var/lib/apt/lists/* +USER dspace # On startup, run DSpace commandline script ENTRYPOINT ["./bin/dspace"] diff --git a/dspace-api/src/main/java/org/dspace/app/statistics/LogAnalyser.java b/dspace-api/src/main/java/org/dspace/app/statistics/LogAnalyser.java index d1a1d6110359..ea7fc67bb657 100644 --- a/dspace-api/src/main/java/org/dspace/app/statistics/LogAnalyser.java +++ b/dspace-api/src/main/java/org/dspace/app/statistics/LogAnalyser.java @@ -16,6 +16,8 @@ import java.sql.SQLException; import java.time.Instant; import java.time.LocalDate; +import java.time.LocalTime; +import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; import java.util.ArrayList; @@ -1083,13 +1085,17 @@ public static LocalDate parseDate(String date) { /** - * Take the date object and convert it into a string of the form YYYY-MM-DD + * Take the date object and convert it into an Instant datetime object of the form YYYY-MM-DDTHH:MM:SSZ * * @param date the date to be converted - * @return A string of the form YYYY-MM-DD + * @return An Instant datetime object of the form YYYY-MM-DDTHH:MM:SSZ */ - public static String unParseDate(LocalDate date) { - return DateTimeFormatter.ISO_LOCAL_DATE.format(date); + public static Instant convertDate(LocalDate date, boolean startOfDay) { + if (startOfDay) { + return date.atStartOfDay(ZoneId.systemDefault()).toInstant(); + } else { + return date.atTime(LocalTime.MAX).atZone(ZoneId.systemDefault()).toInstant(); + } } @@ -1219,13 +1225,13 @@ public static Integer getNumItems(Context context, String type) StringBuilder accessionedQuery = new StringBuilder(); accessionedQuery.append("dc.date.accessioned_dt:["); if (startDate != null) { - accessionedQuery.append(unParseDate(startDate)); + accessionedQuery.append(convertDate(startDate, true)); } else { accessionedQuery.append("*"); } accessionedQuery.append(" TO "); if (endDate != null) { - accessionedQuery.append(unParseDate(endDate)); + accessionedQuery.append(convertDate(endDate, false)); } else { accessionedQuery.append("*"); } diff --git a/dspace-server-webapp/src/main/java/org/dspace/app/rest/health/SEOHealthIndicator.java b/dspace-server-webapp/src/main/java/org/dspace/app/rest/health/SEOHealthIndicator.java index 5b57f2d537fc..d7a3cad84217 100644 --- a/dspace-server-webapp/src/main/java/org/dspace/app/rest/health/SEOHealthIndicator.java +++ b/dspace-server-webapp/src/main/java/org/dspace/app/rest/health/SEOHealthIndicator.java @@ -7,9 +7,13 @@ */ package org.dspace.app.rest.health; +import static org.dspace.app.rest.configuration.ActuatorConfiguration.UP_WITH_ISSUES_STATUS; + +import java.net.URI; + import org.apache.commons.lang3.StringUtils; import org.dspace.services.ConfigurationService; -import org.dspace.services.factory.DSpaceServicesFactory; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.health.AbstractHealthIndicator; import org.springframework.boot.actuate.health.Health; import org.springframework.web.client.RestTemplate; @@ -22,44 +26,63 @@ */ public class SEOHealthIndicator extends AbstractHealthIndicator { - ConfigurationService configurationService = DSpaceServicesFactory.getInstance().getConfigurationService(); + public static final String SITEMAP = "sitemap"; + public static final String ROBOTS_TXT = "robots.txt"; + public static final String SSR = "ssr"; + public static final String OK = "OK"; + public static final String SITEMAP_MISSING = "Sitemaps are missing or inaccessible. Please see the " + + "DSpace Documentation on Search Engine Optimization for how to enable " + + "Sitemaps."; + public static final String ROBOTS_MISSING = "Missing or inaccessible. Please see the DSpace Documentation on " + + "Search Engine Optimization for how to create a robots.txt."; + public static final String ROBOTS_INVALID = "Invalid because it contains localhost URLs. This is often a sign " + + "that a proxy is failing to pass X-Forwarded headers to DSpace. Please see the DSpace " + + "Documentation on Search Engine Optimization for how to pass X-Forwarded headers."; + public static final String SSR_DISABLED = "Server-side rendering (SSR) appears to be disabled. Most " + + "search engines require enabling SSR for proper indexing. Please see the DSpace Documentation on" + + " Search Engine Optimization for more details."; + + @Autowired + private ConfigurationService configurationService; - private final RestTemplate restTemplate = new RestTemplate(); + private RestTemplate restTemplate = new RestTemplate(); @Override protected void doHealthCheck(Health.Builder builder) { String baseUrl = configurationService.getProperty("dspace.ui.url"); boolean sitemapOk = checkUrl(baseUrl + "/sitemap_index.xml") || checkUrl(baseUrl + "/sitemap_index.html"); - RobotsTxtStatus robotsTxtStatus = checkRobotsTxt(baseUrl + "/robots.txt"); + RobotsTxtStatus robotsTxtStatus = checkRobotsTxt(baseUrl); boolean ssrOk = checkSSR(baseUrl); if (sitemapOk && robotsTxtStatus == RobotsTxtStatus.VALID && ssrOk) { builder.up() - .withDetail("sitemap", "OK") - .withDetail("robots.txt", "OK") - .withDetail("ssr", "OK"); + .withDetail(SITEMAP, OK) + .withDetail(ROBOTS_TXT, OK) + .withDetail(SSR, OK); } else { - builder.down(); - builder.withDetail("sitemap", sitemapOk ? "OK" : "Sitemaps are missing or inaccessible. Please see the " + - "DSpace Documentation on Search Engine Optimization for how to enable Sitemaps."); + builder.status(UP_WITH_ISSUES_STATUS) + .withDetail(SITEMAP, sitemapOk ? OK : SITEMAP_MISSING); if (robotsTxtStatus == RobotsTxtStatus.MISSING) { - builder.withDetail("robots.txt", "Missing or inaccessible. Please see the DSpace Documentation on " + - "Search Engine Optimization for how to create a robots.txt."); + builder.withDetail(ROBOTS_TXT, ROBOTS_MISSING); } else if (robotsTxtStatus == RobotsTxtStatus.INVALID) { - builder.withDetail("robots.txt", "Invalid because it contains localhost URLs. This is often a sign " + - "that a proxy is failing to pass X-Forwarded headers to DSpace. Please see the DSpace " + - "Documentation on Search Engine Optimization for how to pass X-Forwarded headers."); + builder.withDetail(ROBOTS_TXT, ROBOTS_INVALID); } else { - builder.withDetail("robots.txt", "OK"); + builder.withDetail(ROBOTS_TXT, OK); } - builder.withDetail("ssr", ssrOk ? "OK" : "Server-side rendering (SSR) appears to be disabled. Most " + - "search engines require enabling SSR for proper indexing. Please see the DSpace Documentation on" + - " Search Engine Optimization for more details."); + builder.withDetail(SSR, ssrOk ? OK : SSR_DISABLED); } } + /** + * Crawlers read robots.txt only from the root of the site, also when the UI runs under a path like /repository. + */ + private String getSiteRoot(String url) { + URI uri = URI.create(url); + return uri.getScheme() + "://" + uri.getRawAuthority(); + } + private boolean checkUrl(String url) { try { restTemplate.getForEntity(url, String.class); @@ -69,10 +92,11 @@ private boolean checkUrl(String url) { } } - private RobotsTxtStatus checkRobotsTxt(String url) { + private RobotsTxtStatus checkRobotsTxt(String baseUrl) { try { - String content = restTemplate.getForObject(url, String.class); - if (StringUtils.isBlank(content)) { + String content = restTemplate.getForObject(getSiteRoot(baseUrl) + "/robots.txt", String.class); + // An HTML page here comes from a catch-all route of the site, not from a real robots.txt. + if (StringUtils.isBlank(content) || content.stripLeading().startsWith("<")) { return RobotsTxtStatus.MISSING; } if (content.contains("localhost")) { diff --git a/dspace-server-webapp/src/test/java/org/dspace/app/rest/HealthIndicatorsIT.java b/dspace-server-webapp/src/test/java/org/dspace/app/rest/HealthIndicatorsIT.java index 0bb679339877..a1b8dbdd4c51 100644 --- a/dspace-server-webapp/src/test/java/org/dspace/app/rest/HealthIndicatorsIT.java +++ b/dspace-server-webapp/src/test/java/org/dspace/app/rest/HealthIndicatorsIT.java @@ -71,4 +71,15 @@ public void testWithAdminUser() throws Exception { ))); } + + @Test + public void testLdapIndicatorIsOff() throws Exception { + + String token = getAuthToken(admin.getEmail(), password); + + getClient(token).perform(get(HEALTH_PATH)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.components.ldap").doesNotExist()); + + } } diff --git a/dspace-server-webapp/src/test/java/org/dspace/app/rest/health/SEOHealthIndicatorTest.java b/dspace-server-webapp/src/test/java/org/dspace/app/rest/health/SEOHealthIndicatorTest.java new file mode 100644 index 000000000000..1da7fc598e8e --- /dev/null +++ b/dspace-server-webapp/src/test/java/org/dspace/app/rest/health/SEOHealthIndicatorTest.java @@ -0,0 +1,165 @@ +/** + * The contents of this file are subject to the license and copyright + * detailed in the LICENSE and NOTICE files at the root of the source + * tree and available online at + * + * http://www.dspace.org/license/ + */ +package org.dspace.app.rest.health; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.when; + +import java.util.Map; + +import org.dspace.app.rest.configuration.ActuatorConfiguration; +import org.dspace.services.ConfigurationService; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.springframework.boot.actuate.health.Health; +import org.springframework.boot.actuate.health.Status; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.RestClientException; +import org.springframework.web.client.RestTemplate; + +/** + * Unit tests for {@link SEOHealthIndicator}. + */ +@RunWith(MockitoJUnitRunner.class) +public class SEOHealthIndicatorTest { + + private static final String BASE_URL = "https://demo.dspace.org"; + + @Mock + private ConfigurationService configurationService; + + @Mock + private RestTemplate restTemplate; + + @InjectMocks + private SEOHealthIndicator seoHealthIndicator; + + @Before + public void setUp() { + when(configurationService.getProperty("dspace.ui.url")).thenReturn(BASE_URL); + } + + @Test + public void testWithSeoConfiguredCorrectly() { + when(restTemplate.getForEntity(anyString(), eq(String.class))) + .thenReturn(ResponseEntity.ok("")); + when(restTemplate.getForObject(eq(BASE_URL + "/robots.txt"), eq(String.class))) + .thenReturn("User-agent: *\nSitemap: " + BASE_URL + "/sitemap_index.xml"); + when(restTemplate.getForObject(eq(BASE_URL), eq(String.class))) + .thenReturn("Rendered content"); + + Health health = seoHealthIndicator.health(); + + assertThat(health.getStatus(), is(Status.UP)); + assertThat(health.getDetails(), is(Map.of( + SEOHealthIndicator.SITEMAP, SEOHealthIndicator.OK, + SEOHealthIndicator.ROBOTS_TXT, SEOHealthIndicator.OK, + SEOHealthIndicator.SSR, SEOHealthIndicator.OK))); + } + + @Test + public void testRobotsTxtIsReadFromSiteRootWhenUiRunsUnderPath() { + String uiUrl = BASE_URL + "/repository"; + when(configurationService.getProperty("dspace.ui.url")).thenReturn(uiUrl); + when(restTemplate.getForEntity(anyString(), eq(String.class))) + .thenReturn(ResponseEntity.ok("")); + when(restTemplate.getForObject(eq(BASE_URL + "/robots.txt"), eq(String.class))) + .thenReturn("User-agent: *\nSitemap: " + uiUrl + "/sitemap_index.xml"); + when(restTemplate.getForObject(eq(uiUrl), eq(String.class))) + .thenReturn("Rendered content"); + + Health health = seoHealthIndicator.health(); + + assertThat(health.getStatus(), is(Status.UP)); + assertThat(health.getDetails().get(SEOHealthIndicator.ROBOTS_TXT), is(SEOHealthIndicator.OK)); + } + + @Test + public void testWithHtmlPageAsRobotsTxtReportsUpWithIssues() { + when(restTemplate.getForEntity(anyString(), eq(String.class))) + .thenReturn(ResponseEntity.ok("")); + when(restTemplate.getForObject(eq(BASE_URL + "/robots.txt"), eq(String.class))) + .thenReturn("Page not found"); + when(restTemplate.getForObject(eq(BASE_URL), eq(String.class))) + .thenReturn("Rendered content"); + + Health health = seoHealthIndicator.health(); + + assertThat(health.getStatus(), is(ActuatorConfiguration.UP_WITH_ISSUES_STATUS)); + assertThat(health.getDetails().get(SEOHealthIndicator.ROBOTS_TXT), is(SEOHealthIndicator.ROBOTS_MISSING)); + } + + @Test + public void testWithoutUiUrlReportsUpWithIssues() { + when(configurationService.getProperty("dspace.ui.url")).thenReturn(null); + + Health health = seoHealthIndicator.health(); + + assertThat(health.getStatus(), is(ActuatorConfiguration.UP_WITH_ISSUES_STATUS)); + assertThat(health.getDetails().get(SEOHealthIndicator.ROBOTS_TXT), is(SEOHealthIndicator.ROBOTS_MISSING)); + } + + @Test + public void testWithSeoChecksFailingReportsUpWithIssues() { + when(restTemplate.getForEntity(anyString(), eq(String.class))) + .thenThrow(new RestClientException("connection refused")); + when(restTemplate.getForObject(anyString(), eq(String.class))) + .thenThrow(new RestClientException("connection refused")); + + Health health = seoHealthIndicator.health(); + + assertThat(health.getStatus(), is(ActuatorConfiguration.UP_WITH_ISSUES_STATUS)); + assertThat(health.getDetails(), is(Map.of( + SEOHealthIndicator.SITEMAP, SEOHealthIndicator.SITEMAP_MISSING, + SEOHealthIndicator.ROBOTS_TXT, SEOHealthIndicator.ROBOTS_MISSING, + SEOHealthIndicator.SSR, SEOHealthIndicator.SSR_DISABLED))); + } + + @Test + public void testWithRobotsTxtContainingLocalhostReportsUpWithIssues() { + when(restTemplate.getForEntity(anyString(), eq(String.class))) + .thenReturn(ResponseEntity.ok("")); + when(restTemplate.getForObject(eq(BASE_URL + "/robots.txt"), eq(String.class))) + .thenReturn("Sitemap: http://localhost:8080/sitemap_index.xml"); + when(restTemplate.getForObject(eq(BASE_URL), eq(String.class))) + .thenReturn("Rendered content"); + + Health health = seoHealthIndicator.health(); + + assertThat(health.getStatus(), is(ActuatorConfiguration.UP_WITH_ISSUES_STATUS)); + assertThat(health.getDetails(), is(Map.of( + SEOHealthIndicator.SITEMAP, SEOHealthIndicator.OK, + SEOHealthIndicator.ROBOTS_TXT, SEOHealthIndicator.ROBOTS_INVALID, + SEOHealthIndicator.SSR, SEOHealthIndicator.OK))); + } + + @Test + public void testWithSsrDisabledReportsUpWithIssues() { + when(restTemplate.getForEntity(anyString(), eq(String.class))) + .thenReturn(ResponseEntity.ok("")); + when(restTemplate.getForObject(eq(BASE_URL + "/robots.txt"), eq(String.class))) + .thenReturn("User-agent: *\nSitemap: " + BASE_URL + "/sitemap_index.xml"); + when(restTemplate.getForObject(eq(BASE_URL), eq(String.class))) + .thenReturn(""); + + Health health = seoHealthIndicator.health(); + + assertThat(health.getStatus(), is(ActuatorConfiguration.UP_WITH_ISSUES_STATUS)); + assertThat(health.getDetails(), is(Map.of( + SEOHealthIndicator.SITEMAP, SEOHealthIndicator.OK, + SEOHealthIndicator.ROBOTS_TXT, SEOHealthIndicator.OK, + SEOHealthIndicator.SSR, SEOHealthIndicator.SSR_DISABLED))); + } +} diff --git a/dspace-server-webapp/src/test/resources/application-test.properties b/dspace-server-webapp/src/test/resources/application-test.properties index ca065187d46c..0128ae1ad7fb 100644 --- a/dspace-server-webapp/src/test/resources/application-test.properties +++ b/dspace-server-webapp/src/test/resources/application-test.properties @@ -16,8 +16,5 @@ ## This file is found on classpath at src/test/resources/log4j2-test.xml logging.config = classpath:log4j2-test.xml -# Disable LDAP Health Check during tests to avoid external LDAP requirement -management.health.ldap.enabled=false - # Our integration tests expect application to be deployed at the root path (/) server.servlet.context-path=/ diff --git a/dspace/bin/make-handle-config b/dspace/bin/make-handle-config index 127034ee5ddb..c65b4ee6cd9a 100755 --- a/dspace/bin/make-handle-config +++ b/dspace/bin/make-handle-config @@ -38,7 +38,7 @@ echo "" >>$tempfile # Dual-stack (IPv4 and IPv6)? (default=n) echo $dshostip >>$tempfile # IP address echo "" >>$tempfile # DBind address (default=same as IP) echo "" >>$tempfile # Port to listen to (default=2641) -echo "" >>$tempfile # Port for HTTP i/f to listen to (default=8000) +echo "8010" >>$tempfile # Port for HTTP i/f to listen to (default=8000, the debug port of the test image) echo "n" >>$tempfile # Log all accesses? ("y" or "n", default=y) echo "" >>$tempfile # Version/serial no. of site (default=1) echo $dsname Handle Server >>$tempfile # Server description diff --git a/dspace/bin/start-handle-server b/dspace/bin/start-handle-server index b2af9cf759b8..598f9a48af4b 100755 --- a/dspace/bin/start-handle-server +++ b/dspace/bin/start-handle-server @@ -22,10 +22,13 @@ HANDLEDIR=`$BINDIR/dspace dsprop --property handle.dir` # If you want your handle server logs stored elsewhere, change this value LOGDIR=$DSPACEDIR/log -#Allow user to specify java options through JAVA_OPTS variable -if [ "$JAVA_OPTS" = "" ]; then +# Unset JAVA_TOOL_OPTIONS (exported by Dockerfile.test) so that its debug port stays free for DSpace +unset JAVA_TOOL_OPTIONS + +# JAVA_OPTS_HANDLE, not JAVA_OPTS: the Docker image sets JAVA_OPTS for the webapp +if [ "$JAVA_OPTS_HANDLE" = "" ]; then #Default Java to use 256MB of memory - JAVA_OPTS=-Xmx256m + JAVA_OPTS_HANDLE=-Xmx256m fi # Remove lock file, in case the old Handle server did not shut down properly @@ -34,7 +37,7 @@ rm -f $HANDLEDIR/txns/lock # Start the Handle server, with a special log4j properties file. # We cannot simply write to the same logs, since log4j # does not support more than one JVM writing to the same rolling log. -nohup java $JAVA_OPTS -classpath `$BINDIR/dspace classpath` \ +nohup java $JAVA_OPTS_HANDLE -classpath `$BINDIR/dspace classpath` \ -Ddspace.log.init.disable=true \ -Dlog4j2.configurationFile=log4j2-handle-plugin.xml \ net.handle.server.Main $HANDLEDIR \ diff --git a/dspace/config/modules/actuator.cfg b/dspace/config/modules/actuator.cfg index c3b19cfc0297..153446b77876 100644 --- a/dspace/config/modules/actuator.cfg +++ b/dspace/config/modules/actuator.cfg @@ -21,6 +21,8 @@ management.endpoint.health.status.http-mapping.out-of-service = 200 management.health.ping.enabled = false management.health.diskSpace.enabled = false +# Spring Boot's own LDAP check does not read authentication-ldap.cfg and fails on localhost:389. +management.health.ldap.enabled = false # CORS configuration for all actuators management.endpoints.web.cors.allowed-origins = ${rest.cors.allowed-origins}