add rest endpoint for renaming repository name and namespace

This commit is contained in:
Eduard Heimbuch
2020-06-23 16:07:38 +02:00
parent fa8311990a
commit 59c0b152f5
10 changed files with 226 additions and 14 deletions

View File

@@ -53,7 +53,7 @@ import java.util.Set;
*/
@StaticPermissions(
value = "repository",
permissions = {"read", "modify", "delete", "healthCheck", "pull", "push", "permissionRead", "permissionWrite"},
permissions = {"read", "modify", "delete", "rename", "healthCheck", "pull", "push", "permissionRead", "permissionWrite"},
custom = true, customGlobal = true
)
@XmlAccessorType(XmlAccessType.FIELD)

View File

@@ -0,0 +1,39 @@
/*
* MIT License
*
* Copyright (c) 2020-present Cloudogu GmbH and Contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package sonia.scm.api.v2.resources;
import lombok.Getter;
import lombok.NoArgsConstructor;
import sonia.scm.util.ValidationUtil;
import javax.validation.constraints.Pattern;
@Getter
@NoArgsConstructor
public class RepositoryRenameDto {
@Pattern(regexp = ValidationUtil.REGEX_REPOSITORYNAME)
private String name;
private String namespace;
}

View File

@@ -24,21 +24,24 @@
package sonia.scm.api.v2.resources;
import com.google.common.base.Strings;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import sonia.scm.config.ScmConfiguration;
import sonia.scm.repository.NamespaceAndName;
import sonia.scm.repository.Repository;
import sonia.scm.repository.RepositoryManager;
import sonia.scm.repository.RepositoryPermissions;
import sonia.scm.web.VndMediaType;
import javax.inject.Inject;
import javax.inject.Provider;
import javax.validation.Valid;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
@@ -59,18 +62,20 @@ public class RepositoryResource {
private final RepositoryManager manager;
private final SingleResourceManagerAdapter<Repository, RepositoryDto> adapter;
private final RepositoryBasedResourceProvider resourceProvider;
private final ScmConfiguration scmConfiguration;
@Inject
public RepositoryResource(
RepositoryToRepositoryDtoMapper repositoryToDtoMapper,
RepositoryDtoToRepositoryMapper dtoToRepositoryMapper, RepositoryManager manager,
RepositoryBasedResourceProvider resourceProvider
) {
RepositoryBasedResourceProvider resourceProvider,
ScmConfiguration scmConfiguration) {
this.dtoToRepositoryMapper = dtoToRepositoryMapper;
this.manager = manager;
this.repositoryToDtoMapper = repositoryToDtoMapper;
this.adapter = new SingleResourceManagerAdapter<>(manager, Repository.class);
this.resourceProvider = resourceProvider;
this.scmConfiguration = scmConfiguration;
}
/**
@@ -80,7 +85,6 @@ public class RepositoryResource {
*
* @param namespace the namespace of the repository
* @param name the name of the repository
*
*/
@GET
@Path("")
@@ -129,7 +133,6 @@ public class RepositoryResource {
*
* @param namespace the namespace of the repository to delete
* @param name the name of the repository to delete
*
*/
@DELETE
@Path("")
@@ -176,6 +179,68 @@ public class RepositoryResource {
);
}
/**
* Renames the given repository.
*
* <strong>Note:</strong> This method requires "repository" privilege.
*
* @param namespace the namespace of the repository to be modified
* @param name the name of the repository to be modified
* @param renameDto renameDto object to modify
*/
@POST
@Path("rename")
@Consumes(VndMediaType.REPOSITORY)
@Operation(summary = "Rename repository", description = "Renames the repository for the given namespace and name.", tags = "Repository")
@ApiResponse(responseCode = "204", description = "update success")
@ApiResponse(responseCode = "400", description = "invalid body, e.g. illegal change of namespace or name")
@ApiResponse(responseCode = "401", description = "not authenticated / invalid credentials")
@ApiResponse(responseCode = "403", description = "not authorized, the current user does not have the \"repository:renameDto\" privilege")
@ApiResponse(
responseCode = "404",
description = "not found, no repository with the specified namespace and name available",
content = @Content(
mediaType = VndMediaType.ERROR_TYPE,
schema = @Schema(implementation = ErrorDto.class)
))
@ApiResponse(responseCode = "500", description = "internal server error")
public Response rename(@PathParam("namespace") String namespace, @PathParam("name") String name, @Valid RepositoryRenameDto renameDto) {
Repository repo = loadBy(namespace, name).get();
if (isRenameForbidden(repo)) {
return Response.status(403).build();
}
if (hasNamespaceOrNameNotChanged(repo, renameDto)) {
return Response.status(400).build();
}
if (!Strings.isNullOrEmpty(renameDto.getName())) {
repo.setName(renameDto.getName());
}
if (!Strings.isNullOrEmpty(renameDto.getNamespace())) {
repo.setNamespace(renameDto.getNamespace());
}
return adapter.update(
loadBy(namespace, name),
existing -> repo,
changed -> true,
r -> r.getNamespaceAndName().logString()
);
}
private boolean hasNamespaceOrNameNotChanged(Repository repo, @Valid RepositoryRenameDto renameDto) {
return repo.getName().equals(renameDto.getName())
&& repo.getNamespace().equals(renameDto.getNamespace());
}
private boolean isRenameForbidden(Repository repo) {
return !scmConfiguration.getNamespaceStrategy().equals("CustomNamespaceStrategy")
|| !RepositoryPermissions.rename(repo).isPermitted();
}
private Repository processUpdate(RepositoryDto repositoryDto, Repository existing) {
Repository changedRepository = dtoToRepositoryMapper.map(repositoryDto, existing.getId());
changedRepository.setPermissions(existing.getPermissions());

View File

@@ -24,12 +24,12 @@
package sonia.scm.api.v2.resources;
import com.google.inject.Inject;
import de.otto.edison.hal.Embedded;
import de.otto.edison.hal.Link;
import de.otto.edison.hal.Links;
import org.mapstruct.Mapper;
import org.mapstruct.ObjectFactory;
import sonia.scm.config.ScmConfiguration;
import sonia.scm.repository.Feature;
import sonia.scm.repository.HealthCheckFailure;
import sonia.scm.repository.Repository;
@@ -41,6 +41,7 @@ import sonia.scm.repository.api.ScmProtocol;
import sonia.scm.web.EdisonHalAppender;
import sonia.scm.web.api.RepositoryToHalMapper;
import javax.inject.Inject;
import java.util.List;
import static de.otto.edison.hal.Embedded.embeddedBuilder;
@@ -56,6 +57,8 @@ public abstract class RepositoryToRepositoryDtoMapper extends BaseMapper<Reposit
@Inject
private ResourceLinks resourceLinks;
@Inject
private ScmConfiguration scmConfiguration;
@Inject
private RepositoryServiceFactory serviceFactory;
abstract HealthCheckFailureDto toDto(HealthCheckFailure failure);
@@ -72,6 +75,13 @@ public abstract class RepositoryToRepositoryDtoMapper extends BaseMapper<Reposit
if (RepositoryPermissions.modify(repository).isPermitted()) {
linksBuilder.single(link("update", resourceLinks.repository().update(repository.getNamespace(), repository.getName())));
}
if (RepositoryPermissions.rename(repository).isPermitted()) {
if (scmConfiguration.getNamespaceStrategy().equals("CustomNamespaceStrategy")) {
linksBuilder.single(link("renameWithNamespace", resourceLinks.repository().rename(repository.getNamespace(), repository.getName())));
} else {
linksBuilder.single(link("rename", resourceLinks.repository().rename(repository.getNamespace(), repository.getName())));
}
}
if (RepositoryPermissions.permissionRead(repository).isPermitted()) {
linksBuilder.single(link("permissions", resourceLinks.repositoryPermission().all(repository.getNamespace(), repository.getName())));
}

View File

@@ -279,6 +279,10 @@ class ResourceLinks {
String update(String namespace, String name) {
return repositoryLinkBuilder.method("getRepositoryResource").parameters(namespace, name).method("update").parameters().href();
}
String rename(String namespace, String name) {
return repositoryLinkBuilder.method("getRepositoryResource").parameters(namespace, name).method("rename").parameters().href();
}
}
RepositoryCollectionLinks repositoryCollection() {

View File

@@ -28,6 +28,7 @@
<verb>read</verb>
<verb>modify</verb>
<verb>delete</verb>
<verb>rename</verb>
<verb>pull</verb>
<verb>push</verb>
<verb>permissionRead</verb>

View File

@@ -35,11 +35,13 @@ import org.jboss.resteasy.mock.MockHttpResponse;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.jupiter.api.Nested;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import sonia.scm.PageResult;
import sonia.scm.config.ScmConfiguration;
import sonia.scm.repository.NamespaceAndName;
import sonia.scm.repository.Repository;
import sonia.scm.repository.RepositoryInitializer;
@@ -62,6 +64,7 @@ import static java.util.Collections.singletonList;
import static java.util.stream.Stream.of;
import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST;
import static javax.servlet.http.HttpServletResponse.SC_CONFLICT;
import static javax.servlet.http.HttpServletResponse.SC_FORBIDDEN;
import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND;
import static javax.servlet.http.HttpServletResponse.SC_NO_CONTENT;
import static javax.servlet.http.HttpServletResponse.SC_OK;
@@ -103,6 +106,8 @@ public class RepositoryRootResourceTest extends RepositoryTestBase {
private ScmPathInfo uriInfo;
@Mock
private RepositoryInitializer repositoryInitializer;
@Mock
private ScmConfiguration scmConfiguration;
@Captor
private ArgumentCaptor<Predicate<Repository>> filterCaptor;
@@ -121,11 +126,13 @@ public class RepositoryRootResourceTest extends RepositoryTestBase {
super.repositoryToDtoMapper = repositoryToDtoMapper;
super.dtoToRepositoryMapper = dtoToRepositoryMapper;
super.manager = repositoryManager;
super.scmConfiguration = scmConfiguration;
RepositoryCollectionToDtoMapper repositoryCollectionToDtoMapper = new RepositoryCollectionToDtoMapper(repositoryToDtoMapper, resourceLinks);
super.repositoryCollectionResource = new RepositoryCollectionResource(repositoryManager, repositoryCollectionToDtoMapper, dtoToRepositoryMapper, resourceLinks, repositoryInitializer);
dispatcher.addSingletonResource(getRepositoryRootResource());
when(serviceFactory.create(any(Repository.class))).thenReturn(service);
when(scmPathInfoStore.get()).thenReturn(uriInfo);
when(scmConfiguration.getNamespaceStrategy()).thenReturn("CustomNamespaceStrategy");
when(uriInfo.getApiRestUri()).thenReturn(URI.create("/x/y"));
SimplePrincipalCollection trillian = new SimplePrincipalCollection("trillian", REALM);
trillian.add(new User("trillian"), REALM);
@@ -372,6 +379,65 @@ public class RepositoryRootResourceTest extends RepositoryTestBase {
assertTrue(response.getContentAsString().contains("\"protocol\":[{\"href\":\"http://\",\"name\":\"http\"},{\"href\":\"ssh://\",\"name\":\"ssh\"}]"));
}
@Test
public void shouldNotRenameRepositoryIfNamespaceStrategyIsNotCustom() throws Exception {
mockRepository("space", "repo");
when(scmConfiguration.getNamespaceStrategy()).thenReturn("UsernameNamespaceStrategy");
URL url = Resources.getResource("sonia/scm/api/v2/rename-repo.json");
byte[] repository = Resources.toByteArray(url);
MockHttpRequest request = MockHttpRequest
.post("/" + RepositoryRootResource.REPOSITORIES_PATH_V2 + "space/repo/rename")
.contentType(VndMediaType.REPOSITORY)
.content(repository);
MockHttpResponse response = new MockHttpResponse();
dispatcher.invoke(request, response);
assertEquals(SC_FORBIDDEN, response.getStatus());
}
@Test
public void shouldNotRenameRepositoryIfNamespaceAndNameDidNotChanged() throws Exception {
mockRepository("space", "x");
when(scmConfiguration.getNamespaceStrategy()).thenReturn("CustomNamespaceStrategy");
URL url = Resources.getResource("sonia/scm/api/v2/rename-repo.json");
byte[] repository = Resources.toByteArray(url);
MockHttpRequest request = MockHttpRequest
.post("/" + RepositoryRootResource.REPOSITORIES_PATH_V2 + "space/x/rename")
.contentType(VndMediaType.REPOSITORY)
.content(repository);
MockHttpResponse response = new MockHttpResponse();
dispatcher.invoke(request, response);
assertEquals(SC_BAD_REQUEST, response.getStatus());
}
@Test
public void shouldRenameRepository() throws Exception {
mockRepository("space", "repo");
when(scmConfiguration.getNamespaceStrategy()).thenReturn("CustomNamespaceStrategy");
URL url = Resources.getResource("sonia/scm/api/v2/rename-repo.json");
byte[] repository = Resources.toByteArray(url);
MockHttpRequest request = MockHttpRequest
.post("/" + RepositoryRootResource.REPOSITORIES_PATH_V2 + "space/repo/rename")
.contentType(VndMediaType.REPOSITORY)
.content(repository);
MockHttpResponse response = new MockHttpResponse();
dispatcher.invoke(request, response);
assertEquals(SC_NO_CONTENT, response.getStatus());
verify(repositoryManager).modify(any(Repository.class));
}
private PageResult<Repository> createSingletonPageResult(Repository repository) {
return new PageResult<>(singletonList(repository), 0);
}

View File

@@ -24,6 +24,7 @@
package sonia.scm.api.v2.resources;
import sonia.scm.config.ScmConfiguration;
import sonia.scm.repository.RepositoryManager;
import static com.google.inject.util.Providers.of;
@@ -46,6 +47,7 @@ abstract class RepositoryTestBase {
IncomingRootResource incomingRootResource;
RepositoryCollectionResource repositoryCollectionResource;
AnnotateResource annotateResource;
ScmConfiguration scmConfiguration;
RepositoryRootResource getRepositoryRootResource() {
@@ -66,8 +68,8 @@ abstract class RepositoryTestBase {
repositoryToDtoMapper,
dtoToRepositoryMapper,
manager,
repositoryBasedResourceProvider
)),
repositoryBasedResourceProvider,
scmConfiguration)),
of(repositoryCollectionResource));
}
}

View File

@@ -33,6 +33,7 @@ import org.junit.Rule;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import sonia.scm.config.ScmConfiguration;
import sonia.scm.repository.HealthCheckFailure;
import sonia.scm.repository.Repository;
import sonia.scm.repository.api.Command;
@@ -72,6 +73,8 @@ public class RepositoryToRepositoryDtoMapperTest {
private ScmPathInfoStore scmPathInfoStore;
@Mock
private ScmPathInfo uriInfo;
@Mock
private ScmConfiguration configuration;
@InjectMocks
private RepositoryToRepositoryDtoMapperImpl mapper;
@@ -83,6 +86,7 @@ public class RepositoryToRepositoryDtoMapperTest {
when(repositoryService.isSupported(any(Command.class))).thenReturn(true);
when(repositoryService.getSupportedProtocols()).thenReturn(of());
when(scmPathInfoStore.get()).thenReturn(uriInfo);
when(configuration.getNamespaceStrategy()).thenReturn("CustomNamespaceStrategy");
when(uriInfo.getApiRestUri()).thenReturn(URI.create("/x/y"));
}
@@ -129,6 +133,23 @@ public class RepositoryToRepositoryDtoMapperTest {
dto.getLinks().getLinkBy("update").get().getHref());
}
@Test
public void shouldCreateRenameLink() {
when(configuration.getNamespaceStrategy()).thenReturn("test");
RepositoryDto dto = mapper.map(createTestRepository());
assertEquals(
"http://example.com/base/v2/repositories/testspace/test/rename",
dto.getLinks().getLinkBy("rename").get().getHref());
}
@Test
public void shouldCreateRenameWithNamespaceLink() {
RepositoryDto dto = mapper.map(createTestRepository());
assertEquals(
"http://example.com/base/v2/repositories/testspace/test/rename",
dto.getLinks().getLinkBy("renameWithNamespace").get().getHref());
}
@Test
public void shouldMapHealthCheck() {
RepositoryDto dto = mapper.map(createTestRepository());

View File

@@ -0,0 +1,4 @@
{
"name": "x",
"namespace": "space"
}