Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -477,13 +477,16 @@ public Handle createHandle(Context context, String handleStr) throws SQLExceptio

@Override
public Handle findByHandleAndMagicToken(Context context, String handle, String token) throws SQLException {
if (StringUtils.isBlank(token)) {
return null;
}
Handle h = findByHandle(context, handle);
if (Objects.isNull(h) || Objects.isNull(h.getUrl()) || !h.getUrl().contains(MAGIC_BEAN)) {
if (Objects.isNull(h) || Objects.isNull(h.getUrl()) || !h.getUrl().startsWith(MAGIC_BEAN)) {
return null;
}
org.dspace.handle.external.Handle magicHandle =
new org.dspace.handle.external.Handle(h.getHandle(), h.getUrl());
if (magicHandle.token.equals(token)) {
if (StringUtils.equals(magicHandle.getToken(), token)) {
return h;
} else {
return null;
Expand Down
77 changes: 73 additions & 4 deletions dspace-api/src/main/java/org/dspace/handle/external/Handle.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
import java.util.Objects;
import java.util.UUID;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.dspace.handle.HandlePlugin;

/**
Expand All @@ -26,6 +28,11 @@
*/
public class Handle {

private static final Logger log = LogManager.getLogger(Handle.class);

private static final int MAGIC_URL_PARTS = 10;
private static final int TOKEN_INDEX = 8;

private String handle;
public String url;
public String title;
Expand All @@ -36,7 +43,7 @@ public class Handle {
public String datasetName;
public String datasetVersion;
public String query;
public String token;
private String token;

public Handle() {

Expand Down Expand Up @@ -65,7 +72,7 @@ public Handle(String handle, String url, String title, String repository, String
public Handle(String handle, String magicURL) {
this.handle = handle;
//similar to HandlePlugin
String[] splits = magicURL.split(MAGIC_BEAN,10);
String[] splits = magicURL.split(MAGIC_BEAN, MAGIC_URL_PARTS);
this.url = splits[splits.length - 1];
this.title = splits[1];
this.repository = splits[2];
Expand All @@ -80,12 +87,58 @@ public Handle(String handle, String magicURL) {
if (isNotBlank(splits[7])) {
this.query = splits[7];
}
if (isNotBlank(splits[8])) {
this.token = splits[8];
// same check as hideToken: in an incomplete magic URL the last part is the target url, not a token
String[] complete = splitMagicUrl(magicURL);
if (Objects.nonNull(complete) && isNotBlank(complete[TOKEN_INDEX])) {
this.token = complete[TOKEN_INDEX];
}
this.subprefix = handle.split("/",2)[1].split("-",2)[0];
}

/**
* Return the url with an empty token, so a magic URL can be shown without the secret that allows updating it.
* @param url handle url, magic or not
* @return the url with the token part left empty, or the url as it is when it is not a magic URL
*/
public static String hideToken(String url) {
String[] splits = splitMagicUrl(url);
if (Objects.isNull(splits)) {
return url;
}
splits[TOKEN_INDEX] = "";
return String.join(MAGIC_BEAN, splits);
}

/**
* Put the stored token back into a magic URL whose token is empty, e.g. one loaded with a hidden token.
* @param url new handle url
* @param storedUrl handle url currently stored in the database
* @return the url with the stored token, or the url as it is when it has its own token or is not a magic URL
*/
public static String restoreToken(String url, String storedUrl) {
String[] splits = splitMagicUrl(url);
String[] storedSplits = splitMagicUrl(storedUrl);
if (Objects.isNull(splits) || Objects.isNull(storedSplits) || isNotBlank(splits[TOKEN_INDEX])) {
return url;
}
splits[TOKEN_INDEX] = storedSplits[TOKEN_INDEX];
return String.join(MAGIC_BEAN, splits);
}

private static String[] splitMagicUrl(String url) {
// as HandlePlugin: only a url that starts with the marker is a magic URL
if (isBlank(url) || !url.startsWith(MAGIC_BEAN)) {
return null;
}
String[] splits = url.split(MAGIC_BEAN, MAGIC_URL_PARTS);
if (splits.length != MAGIC_URL_PARTS) {
// the url is not logged, it may contain the token
log.warn("Magic URL has {} parts instead of {}, it has no token.", splits.length, MAGIC_URL_PARTS);
return null;
}
return splits;
}

/**
* Generate new token and combine the properties into the url with `@magicLindat` string
* @return url with the `@magicLindat` string
Expand Down Expand Up @@ -130,4 +183,20 @@ public String getHandle() {
public void setHandle(String handle) {
this.handle = handle.replace(HandlePlugin.getCanonicalHandlePrefix(),"");
}

/**
* The token is needed to update the handle.
* @return the update token, or null when there is none
*/
public String getToken() {
return token;
}

/**
* Set the token, e.g. from the update request.
* @param token
*/
public void setToken(String token) {
this.token = token;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
*/
package org.dspace.app.rest.converter;

import static org.dspace.handle.external.Handle.hideToken;

import java.util.Objects;

import org.dspace.app.rest.model.HandleRest;
Expand Down Expand Up @@ -36,7 +38,7 @@ public HandleRest convert(Handle modelObject, Projection projection) {
handleRest.setId(modelObject.getID());
handleRest.setHandle(modelObject.getHandle());
handleRest.setResourceTypeID(modelObject.getResourceTypeId());
handleRest.setUrl(modelObject.getUrl());
handleRest.setUrl(hideToken(modelObject.getUrl()));
if (Objects.nonNull(modelObject.getDSpaceObject())) {
handleRest.setResourceId(modelObject.getDSpaceObject().getID());
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ public ResponseEntity<Object> updateHandle(@RequestBody Handle updatedHandle, Ht
}

if (validHandleUrl(updatedHandle.url)
&& isNotBlank(updatedHandle.getHandle()) && isNotBlank(updatedHandle.token)) {
&& isNotBlank(updatedHandle.getHandle()) && isNotBlank(updatedHandle.getToken())) {
try {
// remove canonical prefix from handle string because the handle is stored in the DB without
// the canonical prefix
Expand All @@ -153,7 +153,8 @@ && isNotBlank(updatedHandle.getHandle()) && isNotBlank(updatedHandle.token)) {

// load Handle object from the DB
org.dspace.handle.Handle handleEntity =
this.handleClarinService.findByHandleAndMagicToken(context, oldHandleStr, updatedHandle.token);
this.handleClarinService.findByHandleAndMagicToken(context, oldHandleStr,
updatedHandle.getToken());

if (Objects.isNull(handleEntity)) {
return new ResponseEntity<>("Cannot find the handle in the database.",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
*/
package org.dspace.app.rest.repository;

import static org.dspace.handle.external.Handle.restoreToken;

import java.io.IOException;
import java.lang.invoke.WrongMethodTypeException;
import java.sql.SQLException;
Expand Down Expand Up @@ -73,7 +75,7 @@ public class HandleRestRepository extends DSpaceRestRepository<HandleRest, Inte
* @return handle rest
*/
@Override
@PreAuthorize("permitAll()")
@PreAuthorize("hasAuthority('ADMIN')")
public HandleRest findOne(Context context, Integer id) {
Handle handle;
try {
Expand All @@ -99,7 +101,7 @@ public HandleRest findOne(Context context, Integer id) {
* @return page of handle rest
*/
@Override
@PreAuthorize("permitAll()")
@PreAuthorize("hasAuthority('ADMIN')")
public Page<HandleRest> findAll(Context context, Pageable pageable) {
try {
// Get sorting request into the string variable
Expand Down Expand Up @@ -380,7 +382,7 @@ private void fetchHandleAndUpdate(Context context, Operation operation, Integer

// Update handle based on obtained values from json nodes
this.updateHandle(context, handleObject, jsonNodeHandle.asText(),
handleObject.getDSpaceObject(), jsonNodeUrl.asText(),
handleObject.getDSpaceObject(), restoreToken(jsonNodeUrl.asText(), handleObject.getUrl()),
jsonNodeArchive.asBoolean());
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,14 @@
package org.dspace.app.rest;

import static org.hamcrest.Matchers.anyOf;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.patch;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
Expand All @@ -25,6 +29,7 @@

import com.fasterxml.jackson.databind.ObjectMapper;
import org.dspace.app.rest.matcher.ExternalHandleMatcher;
import org.dspace.app.rest.model.patch.ReplaceOperation;
import org.dspace.app.rest.repository.RandomStringGenerator;
import org.dspace.app.rest.test.AbstractControllerIntegrationTest;
import org.dspace.authorize.AuthorizeException;
Expand Down Expand Up @@ -68,6 +73,7 @@ public class ExternalHandleRestRepositoryIT extends AbstractControllerIntegratio

private final String urlBlacklistConfig = "shortener.post.url.blacklist.regexps";
private final String hostBlacklistConfig = "shortener.post.host.blacklist.regexps";
private static final String TEST_URL = "https://example.org/target";
private String[] urlBlacklist;
private String[] hostBlacklist;

Expand Down Expand Up @@ -297,6 +303,95 @@ public void noTokenInGetResponse() throws Exception {
Assert.assertFalse("Token should not be in the response", content.contains("token0"));
}

@Test
public void coreHandlesEndpointHidesToken() throws Exception {
org.dspace.handle.Handle handle = handlesWithMagicURLs.get(0);
String hiddenUrl = handle.getUrl().replace("token0", "");
String adminToken = getAuthToken(admin.getEmail(), password);

getClient(adminToken).perform(get("/api/core/handles/" + handle.getID()))
.andExpect(status().isOk())
.andExpect(jsonPath("$.url", is(hiddenUrl)));

// the "sort" param is a filter: only handles with the shortener prefix, whatever else is in the DB
getClient(adminToken).perform(get("/api/core/handles").param("sort", "handle:" + prefix))
.andExpect(status().isOk())
.andExpect(jsonPath("$.page.totalElements", is(handlesWithMagicURLs.size())))
.andExpect(jsonPath("$._embedded.handles[*].url", hasItem(hiddenUrl)))
.andExpect(content().string(not(containsString(ExternalHandleConstants.MAGIC_BEAN + "token"))));
}

@Test
public void tokenSetByAdminIsHiddenAndWorksForUpdate() throws Exception {
org.dspace.handle.Handle handle = handlesWithMagicURLs.get(0);
patchUrlAndCheckToken(handle, handle.getUrl().replace("token0", "adminToken"), "adminToken");

allowAnyUrl();
// a new token from the admin is how the old one is withdrawn
updateHandleIsNotFound(handle.getHandle(), "token0");
updateHandle(null, Map.of("handle", handle.getHandle(), "token", "adminToken", "url", TEST_URL));
}

@Test
public void adminSaveOfHiddenUrlKeepsToken() throws Exception {
org.dspace.handle.Handle handle = handlesWithMagicURLs.get(0);
// admin saves the url exactly as the REST API shows it
patchUrlAndCheckToken(handle, handle.getUrl().replace("token0", ""), "token0");

allowAnyUrl();
updateHandle(null, Map.of("handle", handle.getHandle(), "token", "token0", "url", TEST_URL));
}

@Test
public void updateOfHandleWithoutTokenIsNotFound() throws Exception {
String urlWithoutToken = handlesWithMagicURLs.get(0).getUrl().replace("token0", "");
context.turnOffAuthorisationSystem();
org.dspace.handle.Handle handle = ClarinHandleBuilder
.createHandle(context, prefix + "notoken", urlWithoutToken)
.build();
context.commit();
context.restoreAuthSystemState();
getClient(getAuthToken(admin.getEmail(), password)).perform(get("/api/core/handles/" + handle.getID()))
.andExpect(status().isOk());

allowAnyUrl();
updateHandleIsNotFound(handle.getHandle(), "token0");
Assert.assertNull("A missing token must not match an empty token slot",
handleClarinService.findByHandleAndMagicToken(context, handle.getHandle(), null));
}

@Test
public void updateOfHandleWithIncompleteMagicUrlIsNotFound() throws Exception {
// no token part: the last part is the target url, as HandlePlugin reads it
String targetUrl = "https://example.org/old";
String incompleteUrl = handlesWithMagicURLs.get(0).getUrl()
.replace("token0" + ExternalHandleConstants.MAGIC_BEAN + "url0", targetUrl);
context.turnOffAuthorisationSystem();
org.dspace.handle.Handle handle = ClarinHandleBuilder
.createHandle(context, prefix + "incomplete", incompleteUrl)
.build();
context.commit();
context.restoreAuthSystemState();

allowAnyUrl();
updateHandleIsNotFound(handle.getHandle(), targetUrl);
}

@Test
public void updateOfHandleWithMagicMarkerInsideUrlIsNotFound() throws Exception {
// HandlePlugin resolves this as a plain url, so it is not an external handle with a token
String url = TEST_URL + handlesWithMagicURLs.get(0).getUrl();
context.turnOffAuthorisationSystem();
org.dspace.handle.Handle handle = ClarinHandleBuilder
.createHandle(context, prefix + "inside", url)
.build();
context.commit();
context.restoreAuthSystemState();

allowAnyUrl();
updateHandleIsNotFound(handle.getHandle(), "token0");
}

@Test
public void noMagicInCreateResponse() throws Exception {
String url = "https://lindat.mff.cuni.cz/#!/services/pmltq/";
Expand Down Expand Up @@ -381,6 +476,34 @@ private MvcResult updateHandle(String authToken, Map<String, String> updatedHand
;
}

/**
* Update the url as admin, then check that the token is stored but is not in the response.
*/
private void patchUrlAndCheckToken(org.dspace.handle.Handle handle, String url, String token) throws Exception {
Map<String, String> values = Map.of("handle", handle.getHandle(), "url", url, "archive", "false");
getClient(getAuthToken(admin.getEmail(), password))
.perform(patch("/api/core/handles/" + handle.getID())
.content(getPatchContent(List.of(new ReplaceOperation("/updateHandle", values))))
.contentType(jakarta.ws.rs.core.MediaType.APPLICATION_JSON_PATCH_JSON))
.andExpect(status().isOk())
.andExpect(content().string(not(containsString(token))));
Assert.assertTrue("Token should be stored in the database",
handleClarinService.findByHandle(context, handle.getHandle()).getUrl().contains(token));
}

private void updateHandleIsNotFound(String handle, String token) throws Exception {
Map<String, String> update = Map.of("handle", handle, "token", token, "url", TEST_URL);
getClient().perform(put("/api/services/handles")
.content(mapper.writeValueAsBytes(update))
.contentType(contentType))
.andExpect(status().isNotFound());
}

private void allowAnyUrl() {
configurationService.setProperty(urlBlacklistConfig, null);
configurationService.setProperty(hostBlacklistConfig, null);
}

private MvcResult createHandle(String authToken, Map<String, String> handleJson) throws Exception {
return getClient(authToken).perform(post("/api/services/handles")
.content(mapper.writeValueAsBytes(handleJson))
Expand Down
Loading
Loading