mirror of
https://github.com/scm-manager/scm-manager.git
synced 2025-11-17 02:31:14 +01:00
Merge
This commit is contained in:
78
pom.xml
78
pom.xml
@@ -1,5 +1,6 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||||
|
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
|
||||||
@@ -83,7 +84,7 @@
|
|||||||
<name>scm-manager release repository</name>
|
<name>scm-manager release repository</name>
|
||||||
<url>http://maven.scm-manager.org/nexus/content/groups/public</url>
|
<url>http://maven.scm-manager.org/nexus/content/groups/public</url>
|
||||||
</repository>
|
</repository>
|
||||||
|
|
||||||
<repository>
|
<repository>
|
||||||
<id>ossrh</id>
|
<id>ossrh</id>
|
||||||
<url>https://oss.sonatype.org/content/repositories/snapshots</url>
|
<url>https://oss.sonatype.org/content/repositories/snapshots</url>
|
||||||
@@ -118,10 +119,26 @@
|
|||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
|
|
||||||
|
<!-- JUnit 5 -->
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>junit</groupId>
|
<groupId>org.junit.jupiter</groupId>
|
||||||
<artifactId>junit</artifactId>
|
<artifactId>junit-jupiter-api</artifactId>
|
||||||
<scope>test</scope>
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.junit.jupiter</groupId>
|
||||||
|
<artifactId>junit-jupiter-params</artifactId>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.junit.jupiter</groupId>
|
||||||
|
<artifactId>junit-jupiter-engine</artifactId>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.junit.vintage</groupId>
|
||||||
|
<artifactId>junit-vintage-engine</artifactId>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
@@ -139,15 +156,11 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.mockito</groupId>
|
<groupId>org.mockito</groupId>
|
||||||
<artifactId>mockito-core</artifactId>
|
<artifactId>mockito-core</artifactId>
|
||||||
<version>${mockito.version}</version>
|
|
||||||
<scope>test</scope>
|
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.assertj</groupId>
|
<groupId>org.assertj</groupId>
|
||||||
<artifactId>assertj-core</artifactId>
|
<artifactId>assertj-core</artifactId>
|
||||||
<version>3.10.0</version>
|
|
||||||
<scope>test</scope>
|
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
@@ -161,7 +174,7 @@
|
|||||||
<!-- Don't inherit this dependency! -->
|
<!-- Don't inherit this dependency! -->
|
||||||
<scope>provided</scope>
|
<scope>provided</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<dependencyManagement>
|
<dependencyManagement>
|
||||||
@@ -282,9 +295,32 @@
|
|||||||
<version>${jackson.version}</version>
|
<version>${jackson.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
|
<!-- JUnit 5 -->
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>junit</groupId>
|
<groupId>org.junit.jupiter</groupId>
|
||||||
<artifactId>junit</artifactId>
|
<artifactId>junit-jupiter-api</artifactId>
|
||||||
|
<version>${junit.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.junit.jupiter</groupId>
|
||||||
|
<artifactId>junit-jupiter-params</artifactId>
|
||||||
|
<version>${junit.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.junit.jupiter</groupId>
|
||||||
|
<artifactId>junit-jupiter-engine</artifactId>
|
||||||
|
<version>${junit.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.junit.vintage</groupId>
|
||||||
|
<artifactId>junit-vintage-engine</artifactId>
|
||||||
<version>${junit.version}</version>
|
<version>${junit.version}</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
@@ -348,7 +384,11 @@
|
|||||||
</pluginManagement>
|
</pluginManagement>
|
||||||
|
|
||||||
<plugins>
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-surefire-plugin</artifactId>
|
||||||
|
<version>2.22.0</version>
|
||||||
|
</plugin>
|
||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
<artifactId>maven-enforcer-plugin</artifactId>
|
<artifactId>maven-enforcer-plugin</artifactId>
|
||||||
@@ -536,9 +576,9 @@
|
|||||||
<artifactId>maven-eclipse-plugin</artifactId>
|
<artifactId>maven-eclipse-plugin</artifactId>
|
||||||
<version>2.6</version>
|
<version>2.6</version>
|
||||||
</plugin>
|
</plugin>
|
||||||
|
|
||||||
<!-- code coverage -->
|
<!-- code coverage -->
|
||||||
|
|
||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.jacoco</groupId>
|
<groupId>org.jacoco</groupId>
|
||||||
<artifactId>jacoco-maven-plugin</artifactId>
|
<artifactId>jacoco-maven-plugin</artifactId>
|
||||||
@@ -558,7 +598,7 @@
|
|||||||
</execution>
|
</execution>
|
||||||
</executions>
|
</executions>
|
||||||
</plugin>
|
</plugin>
|
||||||
|
|
||||||
<!-- reporting -->
|
<!-- reporting -->
|
||||||
|
|
||||||
<plugin>
|
<plugin>
|
||||||
@@ -695,13 +735,13 @@
|
|||||||
<!-- test libraries -->
|
<!-- test libraries -->
|
||||||
<mockito.version>2.10.0</mockito.version>
|
<mockito.version>2.10.0</mockito.version>
|
||||||
<hamcrest.version>1.3</hamcrest.version>
|
<hamcrest.version>1.3</hamcrest.version>
|
||||||
<junit.version>4.12</junit.version>
|
<junit.version>5.2.0</junit.version>
|
||||||
|
|
||||||
<!-- logging libraries -->
|
<!-- logging libraries -->
|
||||||
<slf4j.version>1.7.22</slf4j.version>
|
<slf4j.version>1.7.22</slf4j.version>
|
||||||
<logback.version>1.1.10</logback.version>
|
<logback.version>1.1.10</logback.version>
|
||||||
<servlet.version>3.0.1</servlet.version>
|
<servlet.version>3.0.1</servlet.version>
|
||||||
|
|
||||||
<jaxrs.version>2.0.1</jaxrs.version>
|
<jaxrs.version>2.0.1</jaxrs.version>
|
||||||
<resteasy.version>3.1.3.Final</resteasy.version>
|
<resteasy.version>3.1.3.Final</resteasy.version>
|
||||||
<jersey-client.version>1.19.4</jersey-client.version>
|
<jersey-client.version>1.19.4</jersey-client.version>
|
||||||
@@ -711,7 +751,7 @@
|
|||||||
|
|
||||||
<!-- event bus -->
|
<!-- event bus -->
|
||||||
<legman.version>1.3.0</legman.version>
|
<legman.version>1.3.0</legman.version>
|
||||||
|
|
||||||
<!-- webserver -->
|
<!-- webserver -->
|
||||||
<jetty.version>9.2.10.v20150310</jetty.version>
|
<jetty.version>9.2.10.v20150310</jetty.version>
|
||||||
<jetty.maven.version>9.2.10.v20150310</jetty.maven.version>
|
<jetty.maven.version>9.2.10.v20150310</jetty.maven.version>
|
||||||
|
|||||||
@@ -1,32 +1,32 @@
|
|||||||
/**
|
/*
|
||||||
* Copyright (c) 2010, Sebastian Sdorra
|
Copyright (c) 2010, Sebastian Sdorra
|
||||||
* All rights reserved.
|
All rights reserved.
|
||||||
*
|
|
||||||
* Redistribution and use in source and binary forms, with or without
|
Redistribution and use in source and binary forms, with or without
|
||||||
* modification, are permitted provided that the following conditions are met:
|
modification, are permitted provided that the following conditions are met:
|
||||||
*
|
|
||||||
* 1. Redistributions of source code must retain the above copyright notice,
|
1. Redistributions of source code must retain the above copyright notice,
|
||||||
* this list of conditions and the following disclaimer.
|
this list of conditions and the following disclaimer.
|
||||||
* 2. Redistributions in binary form must reproduce the above copyright notice,
|
2. Redistributions in binary form must reproduce the above copyright notice,
|
||||||
* this list of conditions and the following disclaimer in the documentation
|
this list of conditions and the following disclaimer in the documentation
|
||||||
* and/or other materials provided with the distribution.
|
and/or other materials provided with the distribution.
|
||||||
* 3. Neither the name of SCM-Manager; nor the names of its
|
3. Neither the name of SCM-Manager; nor the names of its
|
||||||
* contributors may be used to endorse or promote products derived from this
|
contributors may be used to endorse or promote products derived from this
|
||||||
* software without specific prior written permission.
|
software without specific prior written permission.
|
||||||
*
|
|
||||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||||
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||||
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||||
* DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
|
DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
|
||||||
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||||
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||||
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
|
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
|
||||||
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||||
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||||
*
|
|
||||||
* http://bitbucket.org/sdorra/scm-manager
|
http://bitbucket.org/sdorra/scm-manager
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
|
||||||
@@ -36,16 +36,14 @@ package sonia.scm.repository;
|
|||||||
//~--- non-JDK imports --------------------------------------------------------
|
//~--- non-JDK imports --------------------------------------------------------
|
||||||
|
|
||||||
import com.google.common.base.Objects;
|
import com.google.common.base.Objects;
|
||||||
|
|
||||||
import sonia.scm.security.PermissionObject;
|
import sonia.scm.security.PermissionObject;
|
||||||
|
|
||||||
//~--- JDK imports ------------------------------------------------------------
|
|
||||||
|
|
||||||
import java.io.Serializable;
|
|
||||||
|
|
||||||
import javax.xml.bind.annotation.XmlAccessType;
|
import javax.xml.bind.annotation.XmlAccessType;
|
||||||
import javax.xml.bind.annotation.XmlAccessorType;
|
import javax.xml.bind.annotation.XmlAccessorType;
|
||||||
import javax.xml.bind.annotation.XmlRootElement;
|
import javax.xml.bind.annotation.XmlRootElement;
|
||||||
|
import java.io.Serializable;
|
||||||
|
|
||||||
|
//~--- JDK imports ------------------------------------------------------------
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Permissions controls the access to {@link Repository}.
|
* Permissions controls the access to {@link Repository}.
|
||||||
@@ -57,10 +55,11 @@ import javax.xml.bind.annotation.XmlRootElement;
|
|||||||
public class Permission implements PermissionObject, Serializable
|
public class Permission implements PermissionObject, Serializable
|
||||||
{
|
{
|
||||||
|
|
||||||
/** Field description */
|
|
||||||
private static final long serialVersionUID = -2915175031430884040L;
|
private static final long serialVersionUID = -2915175031430884040L;
|
||||||
|
|
||||||
//~--- constructors ---------------------------------------------------------
|
private boolean groupPermission = false;
|
||||||
|
private String name;
|
||||||
|
private PermissionType type = PermissionType.READ;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Constructs a new {@link Permission}.
|
* Constructs a new {@link Permission}.
|
||||||
@@ -153,12 +152,7 @@ public class Permission implements PermissionObject, Serializable
|
|||||||
return Objects.hashCode(name, type, groupPermission);
|
return Objects.hashCode(name, type, groupPermission);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Method description
|
|
||||||
*
|
|
||||||
*
|
|
||||||
* @return
|
|
||||||
*/
|
|
||||||
@Override
|
@Override
|
||||||
public String toString()
|
public String toString()
|
||||||
{
|
{
|
||||||
@@ -242,15 +236,4 @@ public class Permission implements PermissionObject, Serializable
|
|||||||
{
|
{
|
||||||
this.type = type;
|
this.type = type;
|
||||||
}
|
}
|
||||||
|
|
||||||
//~--- fields ---------------------------------------------------------------
|
|
||||||
|
|
||||||
/** Field description */
|
|
||||||
private boolean groupPermission = false;
|
|
||||||
|
|
||||||
/** Field description */
|
|
||||||
private String name;
|
|
||||||
|
|
||||||
/** Field description */
|
|
||||||
private PermissionType type = PermissionType.READ;
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,11 @@
|
|||||||
|
package sonia.scm.repository;
|
||||||
|
|
||||||
|
import java.text.MessageFormat;
|
||||||
|
|
||||||
|
public class PermissionAlreadyExistsException extends RepositoryException {
|
||||||
|
|
||||||
|
public PermissionAlreadyExistsException(Repository repository, String permissionName) {
|
||||||
|
super(MessageFormat.format("the permission {0} of the repository {1}/{2} already exists", permissionName, repository.getNamespace(), repository.getName()));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
package sonia.scm.repository;
|
||||||
|
|
||||||
|
import java.text.MessageFormat;
|
||||||
|
|
||||||
|
public class PermissionNotFoundException extends RepositoryException{
|
||||||
|
|
||||||
|
|
||||||
|
public PermissionNotFoundException(Repository repository, String permissionName) {
|
||||||
|
super(MessageFormat.format("the permission {0} of the repository {1}/{2} does not exists", permissionName,repository.getNamespace(), repository.getName() ));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -42,10 +42,10 @@ public enum PermissionType
|
|||||||
{
|
{
|
||||||
|
|
||||||
/** read permision */
|
/** read permision */
|
||||||
READ(0, "repository:read:"),
|
READ(0, "repository:read,pull:"),
|
||||||
|
|
||||||
/** read and write permissionPrefix */
|
/** read and write permissionPrefix */
|
||||||
WRITE(10, "repository:read,write:"),
|
WRITE(10, "repository:read,pull,push:"),
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* read, write and
|
* read, write and
|
||||||
|
|||||||
@@ -60,7 +60,7 @@ import java.util.List;
|
|||||||
*/
|
*/
|
||||||
@StaticPermissions(
|
@StaticPermissions(
|
||||||
value = "repository",
|
value = "repository",
|
||||||
permissions = {"read", "write", "modify", "delete", "healthCheck"}
|
permissions = {"read", "modify", "delete", "healthCheck", "pull", "push", "permissionRead", "permissionWrite"}
|
||||||
)
|
)
|
||||||
@XmlAccessorType(XmlAccessType.FIELD)
|
@XmlAccessorType(XmlAccessType.FIELD)
|
||||||
@XmlRootElement(name = "repositories")
|
@XmlRootElement(name = "repositories")
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ public class VndMediaType {
|
|||||||
public static final String USER = PREFIX + "user" + SUFFIX;
|
public static final String USER = PREFIX + "user" + SUFFIX;
|
||||||
public static final String GROUP = PREFIX + "group" + SUFFIX;
|
public static final String GROUP = PREFIX + "group" + SUFFIX;
|
||||||
public static final String REPOSITORY = PREFIX + "repository" + SUFFIX;
|
public static final String REPOSITORY = PREFIX + "repository" + SUFFIX;
|
||||||
|
public static final String PERMISSION = PREFIX + "permission" + SUFFIX;
|
||||||
public static final String BRANCH = PREFIX + "branch" + SUFFIX;
|
public static final String BRANCH = PREFIX + "branch" + SUFFIX;
|
||||||
public static final String USER_COLLECTION = PREFIX + "userCollection" + SUFFIX;
|
public static final String USER_COLLECTION = PREFIX + "userCollection" + SUFFIX;
|
||||||
public static final String GROUP_COLLECTION = PREFIX + "groupCollection" + SUFFIX;
|
public static final String GROUP_COLLECTION = PREFIX + "groupCollection" + SUFFIX;
|
||||||
|
|||||||
@@ -36,13 +36,11 @@ package sonia.scm.web.filter;
|
|||||||
//~--- non-JDK imports --------------------------------------------------------
|
//~--- non-JDK imports --------------------------------------------------------
|
||||||
|
|
||||||
import com.google.common.base.Splitter;
|
import com.google.common.base.Splitter;
|
||||||
|
|
||||||
import org.apache.shiro.SecurityUtils;
|
import org.apache.shiro.SecurityUtils;
|
||||||
|
import org.apache.shiro.authz.AuthorizationException;
|
||||||
import org.apache.shiro.subject.Subject;
|
import org.apache.shiro.subject.Subject;
|
||||||
|
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
import sonia.scm.ArgumentIsInvalidException;
|
import sonia.scm.ArgumentIsInvalidException;
|
||||||
import sonia.scm.SCMContext;
|
import sonia.scm.SCMContext;
|
||||||
import sonia.scm.config.ScmConfiguration;
|
import sonia.scm.config.ScmConfiguration;
|
||||||
@@ -53,17 +51,14 @@ import sonia.scm.security.ScmSecurityException;
|
|||||||
import sonia.scm.util.HttpUtil;
|
import sonia.scm.util.HttpUtil;
|
||||||
import sonia.scm.util.Util;
|
import sonia.scm.util.Util;
|
||||||
|
|
||||||
//~--- JDK imports ------------------------------------------------------------
|
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
|
|
||||||
import java.util.Iterator;
|
|
||||||
|
|
||||||
import javax.servlet.FilterChain;
|
import javax.servlet.FilterChain;
|
||||||
import javax.servlet.ServletException;
|
import javax.servlet.ServletException;
|
||||||
import javax.servlet.http.HttpServletRequest;
|
import javax.servlet.http.HttpServletRequest;
|
||||||
import javax.servlet.http.HttpServletResponse;
|
import javax.servlet.http.HttpServletResponse;
|
||||||
import org.apache.shiro.authz.AuthorizationException;
|
import java.io.IOException;
|
||||||
|
import java.util.Iterator;
|
||||||
|
|
||||||
|
//~--- JDK imports ------------------------------------------------------------
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Abstract http filter to check repository permissions.
|
* Abstract http filter to check repository permissions.
|
||||||
@@ -339,7 +334,7 @@ public abstract class PermissionFilter extends HttpFilter
|
|||||||
|
|
||||||
if (writeRequest)
|
if (writeRequest)
|
||||||
{
|
{
|
||||||
permitted = RepositoryPermissions.write(repository).isPermitted();
|
permitted = RepositoryPermissions.push(repository).isPermitted();
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
|
|||||||
225
scm-it/src/test/java/sonia/scm/it/PermissionsITCase.java
Normal file
225
scm-it/src/test/java/sonia/scm/it/PermissionsITCase.java
Normal file
@@ -0,0 +1,225 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2010, Sebastian Sdorra
|
||||||
|
* All rights reserved.
|
||||||
|
*
|
||||||
|
* Redistribution and use in source and binary forms, with or without
|
||||||
|
* modification, are permitted provided that the following conditions are met:
|
||||||
|
*
|
||||||
|
* 1. Redistributions of source code must retain the above copyright notice,
|
||||||
|
* this list of conditions and the following disclaimer.
|
||||||
|
* 2. Redistributions in binary form must reproduce the above copyright notice,
|
||||||
|
* this list of conditions and the following disclaimer in the documentation
|
||||||
|
* and/or other materials provided with the distribution.
|
||||||
|
* 3. Neither the name of SCM-Manager; nor the names of its
|
||||||
|
* contributors may be used to endorse or promote products derived from this
|
||||||
|
* software without specific prior written permission.
|
||||||
|
*
|
||||||
|
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||||
|
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||||
|
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||||
|
* DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
|
||||||
|
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||||
|
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||||
|
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
|
||||||
|
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||||
|
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||||
|
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||||
|
*
|
||||||
|
* http://bitbucket.org/sdorra/scm-manager
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
package sonia.scm.it;
|
||||||
|
|
||||||
|
import org.apache.http.HttpStatus;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Rule;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.junit.rules.TemporaryFolder;
|
||||||
|
import org.junit.runner.RunWith;
|
||||||
|
import org.junit.runners.Parameterized;
|
||||||
|
import org.junit.runners.Parameterized.Parameters;
|
||||||
|
import sonia.scm.repository.PermissionType;
|
||||||
|
import sonia.scm.repository.client.api.RepositoryClient;
|
||||||
|
import sonia.scm.repository.client.api.RepositoryClientException;
|
||||||
|
import sonia.scm.web.VndMediaType;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.util.Collection;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertNull;
|
||||||
|
import static sonia.scm.it.RepositoryUtil.addAndCommitRandomFile;
|
||||||
|
import static sonia.scm.it.RestUtil.given;
|
||||||
|
import static sonia.scm.it.ScmTypes.availableScmTypes;
|
||||||
|
import static sonia.scm.it.TestData.USER_SCM_ADMIN;
|
||||||
|
import static sonia.scm.it.TestData.callRepository;
|
||||||
|
|
||||||
|
@RunWith(Parameterized.class)
|
||||||
|
public class PermissionsITCase {
|
||||||
|
|
||||||
|
public static final String USER_READ = "user_read";
|
||||||
|
public static final String USER_PASS = "pass";
|
||||||
|
private static final String USER_WRITE = "user_write";
|
||||||
|
private static final String USER_OWNER = "user_owner";
|
||||||
|
private static final String USER_OTHER = "user_other";
|
||||||
|
|
||||||
|
@Rule
|
||||||
|
public TemporaryFolder temporaryFolder = new TemporaryFolder();
|
||||||
|
|
||||||
|
private final String repositoryType;
|
||||||
|
private int createdPermissions;
|
||||||
|
|
||||||
|
|
||||||
|
public PermissionsITCase(String repositoryType) {
|
||||||
|
this.repositoryType = repositoryType;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Parameters(name = "{0}")
|
||||||
|
public static Collection<String> createParameters() {
|
||||||
|
return availableScmTypes();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void prepareEnvironment() {
|
||||||
|
TestData.createDefault();
|
||||||
|
TestData.createUser(USER_READ, USER_PASS);
|
||||||
|
TestData.createUserPermission(USER_READ, PermissionType.READ, repositoryType);
|
||||||
|
TestData.createUser(USER_WRITE, USER_PASS);
|
||||||
|
TestData.createUserPermission(USER_WRITE, PermissionType.WRITE, repositoryType);
|
||||||
|
TestData.createUser(USER_OWNER, USER_PASS);
|
||||||
|
TestData.createUserPermission(USER_OWNER, PermissionType.OWNER, repositoryType);
|
||||||
|
TestData.createUser(USER_OTHER, USER_PASS);
|
||||||
|
createdPermissions = 3;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void readUserShouldNotSeePermissions() {
|
||||||
|
assertNull(callRepository(USER_READ, USER_PASS, repositoryType, HttpStatus.SC_OK)
|
||||||
|
.extract()
|
||||||
|
.body().jsonPath().getString("_links.permissions.href"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void readUserShouldNotSeeBruteForcePermissions() {
|
||||||
|
given(VndMediaType.PERMISSION, USER_READ, USER_PASS)
|
||||||
|
.when()
|
||||||
|
.get(TestData.getDefaultPermissionUrl(USER_SCM_ADMIN, USER_SCM_ADMIN, repositoryType))
|
||||||
|
.then()
|
||||||
|
.statusCode(HttpStatus.SC_FORBIDDEN);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void writeUserShouldNotSeePermissions() {
|
||||||
|
assertNull(callRepository(USER_WRITE, USER_PASS, repositoryType, HttpStatus.SC_OK)
|
||||||
|
.extract()
|
||||||
|
.body().jsonPath().getString("_links.permissions.href"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void writeUserShouldNotSeeBruteForcePermissions() {
|
||||||
|
given(VndMediaType.PERMISSION, USER_WRITE, USER_PASS)
|
||||||
|
.when()
|
||||||
|
.get(TestData.getDefaultPermissionUrl(USER_SCM_ADMIN, USER_SCM_ADMIN, repositoryType))
|
||||||
|
.then()
|
||||||
|
.statusCode(HttpStatus.SC_FORBIDDEN);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void ownerShouldSeePermissions() {
|
||||||
|
List<Object> userPermissions = TestData.getUserPermissions(USER_OWNER, USER_PASS, repositoryType);
|
||||||
|
assertEquals(userPermissions.size(), createdPermissions);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void otherUserShouldNotSeeRepository() {
|
||||||
|
callRepository(USER_OTHER, USER_PASS, repositoryType, HttpStatus.SC_FORBIDDEN);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void otherUserShouldNotSeeBruteForcePermissions() {
|
||||||
|
given(VndMediaType.PERMISSION, USER_OTHER, USER_PASS)
|
||||||
|
.when()
|
||||||
|
.get(TestData.getDefaultPermissionUrl(USER_SCM_ADMIN, USER_SCM_ADMIN, repositoryType))
|
||||||
|
.then()
|
||||||
|
.statusCode(HttpStatus.SC_FORBIDDEN);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void readUserShouldCloneRepository() throws IOException {
|
||||||
|
RepositoryClient client = RepositoryUtil.createRepositoryClient(repositoryType, temporaryFolder.newFolder(), USER_READ, USER_PASS);
|
||||||
|
assertEquals(1, Objects.requireNonNull(client.getWorkingCopy().list()).length);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void writeUserShouldCloneRepository() throws IOException {
|
||||||
|
RepositoryClient client = RepositoryUtil.createRepositoryClient(repositoryType, temporaryFolder.newFolder(), USER_WRITE, USER_PASS);
|
||||||
|
assertEquals(1, Objects.requireNonNull(client.getWorkingCopy().list()).length);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void ownerShouldCloneRepository() throws IOException {
|
||||||
|
RepositoryClient client = RepositoryUtil.createRepositoryClient(repositoryType, temporaryFolder.newFolder(), USER_OWNER, USER_PASS);
|
||||||
|
assertEquals(1, Objects.requireNonNull(client.getWorkingCopy().list()).length);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void otherUserShouldNotCloneRepository() {
|
||||||
|
TestData.callRepository(USER_OTHER, USER_PASS, repositoryType, HttpStatus.SC_FORBIDDEN);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected = RepositoryClientException.class)
|
||||||
|
public void userWithReadPermissionShouldBeNotAuthorizedToCommit() throws IOException {
|
||||||
|
createAndCommit(USER_READ);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void userWithOwnerPermissionShouldBeAuthorizedToCommit() throws IOException {
|
||||||
|
createAndCommit(USER_OWNER);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void userWithWritePermissionShouldBeAuthorizedToCommit() throws IOException {
|
||||||
|
createAndCommit(USER_WRITE);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void createAndCommit(String username) throws IOException {
|
||||||
|
RepositoryClient client = RepositoryUtil.createRepositoryClient(repositoryType, temporaryFolder.newFolder(), username, PermissionsITCase.USER_PASS);
|
||||||
|
addAndCommitRandomFile(client, username);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void userWithOwnerPermissionShouldBeAuthorizedToDeleteRepository(){
|
||||||
|
assertDeleteRepositoryOperation(HttpStatus.SC_NO_CONTENT, HttpStatus.SC_NOT_FOUND, USER_OWNER, repositoryType);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void userWithReadPermissionShouldNotBeAuthorizedToDeleteRepository(){
|
||||||
|
assertDeleteRepositoryOperation(HttpStatus.SC_FORBIDDEN, HttpStatus.SC_OK, USER_READ, repositoryType);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void userWithWritePermissionShouldNotBeAuthorizedToDeleteRepository(){
|
||||||
|
assertDeleteRepositoryOperation(HttpStatus.SC_FORBIDDEN, HttpStatus.SC_OK, USER_WRITE, repositoryType);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void assertDeleteRepositoryOperation(int expectedDeleteStatus, int expectedGetStatus, String user, String repositoryType) {
|
||||||
|
given(VndMediaType.REPOSITORY, user, PermissionsITCase.USER_PASS)
|
||||||
|
|
||||||
|
.when()
|
||||||
|
.delete(TestData.getDefaultRepositoryUrl(repositoryType))
|
||||||
|
|
||||||
|
.then()
|
||||||
|
.statusCode(expectedDeleteStatus);
|
||||||
|
|
||||||
|
given(VndMediaType.REPOSITORY, user, PermissionsITCase.USER_PASS)
|
||||||
|
|
||||||
|
.when()
|
||||||
|
.get(TestData.getDefaultRepositoryUrl(repositoryType))
|
||||||
|
|
||||||
|
.then()
|
||||||
|
.statusCode(expectedGetStatus);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -34,6 +34,7 @@ package sonia.scm.it;
|
|||||||
//~--- non-JDK imports --------------------------------------------------------
|
//~--- non-JDK imports --------------------------------------------------------
|
||||||
|
|
||||||
import org.apache.http.HttpStatus;
|
import org.apache.http.HttpStatus;
|
||||||
|
import org.assertj.core.api.Assertions;
|
||||||
import org.junit.Before;
|
import org.junit.Before;
|
||||||
import org.junit.Rule;
|
import org.junit.Rule;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
@@ -41,17 +42,12 @@ import org.junit.rules.TemporaryFolder;
|
|||||||
import org.junit.runner.RunWith;
|
import org.junit.runner.RunWith;
|
||||||
import org.junit.runners.Parameterized;
|
import org.junit.runners.Parameterized;
|
||||||
import org.junit.runners.Parameterized.Parameters;
|
import org.junit.runners.Parameterized.Parameters;
|
||||||
import sonia.scm.repository.Person;
|
|
||||||
import sonia.scm.repository.client.api.ClientCommand;
|
|
||||||
import sonia.scm.repository.client.api.RepositoryClient;
|
import sonia.scm.repository.client.api.RepositoryClient;
|
||||||
import sonia.scm.repository.client.api.RepositoryClientFactory;
|
|
||||||
import sonia.scm.web.VndMediaType;
|
import sonia.scm.web.VndMediaType;
|
||||||
|
|
||||||
import java.io.File;
|
|
||||||
import java.io.FileOutputStream;
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.util.Collection;
|
import java.util.Collection;
|
||||||
import java.util.UUID;
|
import java.util.Objects;
|
||||||
|
|
||||||
import static org.hamcrest.Matchers.equalTo;
|
import static org.hamcrest.Matchers.equalTo;
|
||||||
import static org.hamcrest.Matchers.is;
|
import static org.hamcrest.Matchers.is;
|
||||||
@@ -66,8 +62,6 @@ import static sonia.scm.it.TestData.repositoryJson;
|
|||||||
@RunWith(Parameterized.class)
|
@RunWith(Parameterized.class)
|
||||||
public class RepositoriesITCase {
|
public class RepositoriesITCase {
|
||||||
|
|
||||||
public static final Person AUTHOR = new Person("SCM Administrator", "scmadmin@scm-manager.org");
|
|
||||||
|
|
||||||
@Rule
|
@Rule
|
||||||
public TemporaryFolder temporaryFolder = new TemporaryFolder();
|
public TemporaryFolder temporaryFolder = new TemporaryFolder();
|
||||||
|
|
||||||
@@ -142,57 +136,16 @@ public class RepositoriesITCase {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void shouldCloneRepository() throws IOException {
|
public void shouldCloneRepository() throws IOException {
|
||||||
RepositoryClient client = createRepositoryClient();
|
RepositoryClient client = RepositoryUtil.createRepositoryClient(repositoryType, temporaryFolder.getRoot());
|
||||||
assertEquals("expected metadata dir", 1, client.getWorkingCopy().list().length);
|
assertEquals("expected metadata dir", 1, Objects.requireNonNull(client.getWorkingCopy().list()).length);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void shouldCommitFiles() throws IOException {
|
public void shouldCommitFiles() throws IOException {
|
||||||
RepositoryClient client = createRepositoryClient();
|
RepositoryClient client = RepositoryUtil.createRepositoryClient(repositoryType, temporaryFolder.newFolder(), "scmadmin", "scmadmin");
|
||||||
|
String name = RepositoryUtil.addAndCommitRandomFile(client, "scmadmin");
|
||||||
for (int i = 0; i < 5; i++) {
|
RepositoryClient checkClient = RepositoryUtil.createRepositoryClient(repositoryType, temporaryFolder.newFolder(), "scmadmin", "scmadmin");
|
||||||
createRandomFile(client);
|
Assertions.assertThat(checkClient.getWorkingCopy().list()).contains(name);
|
||||||
}
|
|
||||||
|
|
||||||
commit(client);
|
|
||||||
|
|
||||||
RepositoryClient checkClient = createRepositoryClient();
|
|
||||||
assertEquals("expected 5 files and metadata dir", 6, checkClient.getWorkingCopy().list().length);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void createRandomFile(RepositoryClient client) throws IOException {
|
|
||||||
String uuid = UUID.randomUUID().toString();
|
|
||||||
String name = "file-" + uuid + ".uuid";
|
|
||||||
|
|
||||||
File file = new File(client.getWorkingCopy(), name);
|
|
||||||
try (FileOutputStream out = new FileOutputStream(file)) {
|
|
||||||
out.write(uuid.getBytes());
|
|
||||||
}
|
|
||||||
|
|
||||||
client.getAddCommand().add(name);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static void commit(RepositoryClient repositoryClient) throws IOException {
|
|
||||||
repositoryClient.getCommitCommand().commit(AUTHOR, "commit");
|
|
||||||
if ( repositoryClient.isCommandSupported(ClientCommand.PUSH) ) {
|
|
||||||
repositoryClient.getPushCommand().push();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private RepositoryClient createRepositoryClient() throws IOException {
|
|
||||||
RepositoryClientFactory clientFactory = new RepositoryClientFactory();
|
|
||||||
String cloneUrl = readCloneUrl();
|
|
||||||
return clientFactory.create(repositoryType, cloneUrl, "scmadmin", "scmadmin", temporaryFolder.newFolder());
|
|
||||||
}
|
|
||||||
|
|
||||||
private String readCloneUrl() {
|
|
||||||
return given(VndMediaType.REPOSITORY)
|
|
||||||
|
|
||||||
.when()
|
|
||||||
.get(repositoryUrl)
|
|
||||||
|
|
||||||
.then()
|
|
||||||
.extract()
|
|
||||||
.path("_links.httpProtocol.href");
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,20 +1,23 @@
|
|||||||
package sonia.scm.it;
|
package sonia.scm.it;
|
||||||
|
|
||||||
import org.apache.http.HttpStatus;
|
import org.apache.http.HttpStatus;
|
||||||
|
import org.junit.Assume;
|
||||||
import org.junit.Before;
|
import org.junit.Before;
|
||||||
import org.junit.Rule;
|
import org.junit.Rule;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
import org.junit.rules.TemporaryFolder;
|
import org.junit.rules.TemporaryFolder;
|
||||||
import org.junit.runner.RunWith;
|
import org.junit.runner.RunWith;
|
||||||
import org.junit.runners.Parameterized;
|
import org.junit.runners.Parameterized;
|
||||||
|
import sonia.scm.repository.client.api.ClientCommand;
|
||||||
|
import sonia.scm.repository.client.api.RepositoryClient;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.util.Collection;
|
import java.util.Collection;
|
||||||
|
|
||||||
import static java.lang.Thread.sleep;
|
import static java.lang.Thread.sleep;
|
||||||
import static org.hamcrest.Matchers.equalTo;
|
import static org.hamcrest.Matchers.equalTo;
|
||||||
import static org.junit.Assert.assertNotNull;
|
import static org.junit.Assert.assertNotNull;
|
||||||
import static org.junit.Assume.assumeFalse;
|
|
||||||
import static sonia.scm.it.RestUtil.given;
|
import static sonia.scm.it.RestUtil.given;
|
||||||
import static sonia.scm.it.ScmTypes.availableScmTypes;
|
import static sonia.scm.it.ScmTypes.availableScmTypes;
|
||||||
|
|
||||||
@@ -25,7 +28,7 @@ public class RepositoryAccessITCase {
|
|||||||
public TemporaryFolder tempFolder = new TemporaryFolder();
|
public TemporaryFolder tempFolder = new TemporaryFolder();
|
||||||
|
|
||||||
private final String repositoryType;
|
private final String repositoryType;
|
||||||
private RepositoryUtil repositoryUtil;
|
private File folder;
|
||||||
|
|
||||||
public RepositoryAccessITCase(String repositoryType) {
|
public RepositoryAccessITCase(String repositoryType) {
|
||||||
this.repositoryType = repositoryType;
|
this.repositoryType = repositoryType;
|
||||||
@@ -37,16 +40,18 @@ public class RepositoryAccessITCase {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Before
|
@Before
|
||||||
public void initClient() throws IOException {
|
public void initClient() {
|
||||||
TestData.createDefault();
|
TestData.createDefault();
|
||||||
repositoryUtil = new RepositoryUtil(repositoryType, tempFolder.getRoot());
|
folder = tempFolder.getRoot();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void shouldFindBranches() throws IOException {
|
public void shouldFindBranches() throws IOException {
|
||||||
assumeFalse("There are no branches for SVN", repositoryType.equals("svn"));
|
RepositoryClient repositoryClient = RepositoryUtil.createRepositoryClient(repositoryType, folder);
|
||||||
|
|
||||||
repositoryUtil.createAndCommitFile("a.txt", "a");
|
Assume.assumeTrue("There are no branches for " + repositoryType, repositoryClient.isCommandSupported(ClientCommand.BRANCH));
|
||||||
|
|
||||||
|
RepositoryUtil.createAndCommitFile(repositoryClient, "scmadmin", "a.txt", "a");
|
||||||
|
|
||||||
String branchesUrl = given()
|
String branchesUrl = given()
|
||||||
.when()
|
.when()
|
||||||
@@ -69,9 +74,10 @@ public class RepositoryAccessITCase {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void shouldReadContent() throws IOException, InterruptedException {
|
public void shouldReadContent() throws IOException, InterruptedException {
|
||||||
repositoryUtil.createAndCommitFile("a.txt", "a");
|
RepositoryClient repositoryClient = RepositoryUtil.createRepositoryClient(repositoryType, folder);
|
||||||
|
RepositoryUtil.createAndCommitFile(repositoryClient, "scmadmin", "a.txt", "a");
|
||||||
tempFolder.newFolder("subfolder");
|
tempFolder.newFolder("subfolder");
|
||||||
repositoryUtil.createAndCommitFile("subfolder/a.txt", "sub-a");
|
RepositoryUtil.createAndCommitFile(repositoryClient, "scmadmin", "subfolder/a.txt", "sub-a");
|
||||||
|
|
||||||
sleep(1000);
|
sleep(1000);
|
||||||
|
|
||||||
@@ -111,7 +117,6 @@ public class RepositoryAccessITCase {
|
|||||||
.statusCode(HttpStatus.SC_OK)
|
.statusCode(HttpStatus.SC_OK)
|
||||||
.extract()
|
.extract()
|
||||||
.path("files[0]._links.self.href");
|
.path("files[0]._links.self.href");
|
||||||
System.out.println(subfolderContentUrl);
|
|
||||||
given()
|
given()
|
||||||
.when()
|
.when()
|
||||||
.get(subfolderContentUrl)
|
.get(subfolderContentUrl)
|
||||||
|
|||||||
@@ -8,56 +8,48 @@ import sonia.scm.repository.Person;
|
|||||||
import sonia.scm.repository.client.api.ClientCommand;
|
import sonia.scm.repository.client.api.ClientCommand;
|
||||||
import sonia.scm.repository.client.api.RepositoryClient;
|
import sonia.scm.repository.client.api.RepositoryClient;
|
||||||
import sonia.scm.repository.client.api.RepositoryClientFactory;
|
import sonia.scm.repository.client.api.RepositoryClientFactory;
|
||||||
import sonia.scm.web.VndMediaType;
|
|
||||||
|
|
||||||
import java.io.File;
|
import java.io.File;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
import java.util.UUID;
|
||||||
import static sonia.scm.it.RestUtil.ADMIN_PASSWORD;
|
|
||||||
import static sonia.scm.it.RestUtil.ADMIN_USERNAME;
|
|
||||||
import static sonia.scm.it.RestUtil.given;
|
|
||||||
|
|
||||||
public class RepositoryUtil {
|
public class RepositoryUtil {
|
||||||
|
|
||||||
private static final RepositoryClientFactory REPOSITORY_CLIENT_FACTORY = new RepositoryClientFactory();
|
private static final RepositoryClientFactory REPOSITORY_CLIENT_FACTORY = new RepositoryClientFactory();
|
||||||
|
|
||||||
private final RepositoryClient repositoryClient;
|
static RepositoryClient createRepositoryClient(String repositoryType, File folder) throws IOException {
|
||||||
private final File folder;
|
return createRepositoryClient(repositoryType, folder, "scmadmin", "scmadmin");
|
||||||
|
|
||||||
RepositoryUtil(String repositoryType, File folder) throws IOException {
|
|
||||||
this.repositoryClient = createRepositoryClient(repositoryType, folder);
|
|
||||||
this.folder = folder;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
static RepositoryClient createRepositoryClient(String repositoryType, File folder) throws IOException {
|
static RepositoryClient createRepositoryClient(String repositoryType, File folder, String username, String password) throws IOException {
|
||||||
String httpProtocolUrl = given(VndMediaType.REPOSITORY)
|
String httpProtocolUrl = TestData.callRepository(username, password, repositoryType, HttpStatus.SC_OK)
|
||||||
|
|
||||||
.when()
|
|
||||||
.get(TestData.getDefaultRepositoryUrl(repositoryType))
|
|
||||||
|
|
||||||
.then()
|
|
||||||
.statusCode(HttpStatus.SC_OK)
|
|
||||||
.extract()
|
.extract()
|
||||||
.path("_links.httpProtocol.href");
|
.path("_links.httpProtocol.href");
|
||||||
|
|
||||||
|
return REPOSITORY_CLIENT_FACTORY.create(repositoryType, httpProtocolUrl, username, password, folder);
|
||||||
return REPOSITORY_CLIENT_FACTORY.create(repositoryType, httpProtocolUrl, ADMIN_USERNAME, ADMIN_PASSWORD, folder);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void createAndCommitFile(String fileName, String content) throws IOException {
|
static String addAndCommitRandomFile(RepositoryClient client, String username) throws IOException {
|
||||||
File file = new File(folder, fileName);
|
String uuid = UUID.randomUUID().toString();
|
||||||
|
String name = "file-" + uuid + ".uuid";
|
||||||
|
createAndCommitFile(client, username, name, uuid);
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void createAndCommitFile(RepositoryClient repositoryClient, String username, String fileName, String content) throws IOException {
|
||||||
|
File file = new File(repositoryClient.getWorkingCopy(), fileName);
|
||||||
Files.write(content, file, Charsets.UTF_8);
|
Files.write(content, file, Charsets.UTF_8);
|
||||||
addWithParentDirectories(file);
|
addWithParentDirectories(repositoryClient, file);
|
||||||
commit("added " + fileName);
|
commit(repositoryClient, username, "added " + fileName);
|
||||||
}
|
}
|
||||||
|
|
||||||
private String addWithParentDirectories(File file) throws IOException {
|
private static String addWithParentDirectories(RepositoryClient repositoryClient, File file) throws IOException {
|
||||||
File parent = file.getParentFile();
|
File parent = file.getParentFile();
|
||||||
String thisName = file.getName();
|
String thisName = file.getName();
|
||||||
String path;
|
String path;
|
||||||
if (!folder.equals(parent)) {
|
if (!repositoryClient.getWorkingCopy().equals(parent)) {
|
||||||
addWithParentDirectories(parent);
|
addWithParentDirectories(repositoryClient, parent);
|
||||||
path = addWithParentDirectories(parent) + File.separator + thisName;
|
path = addWithParentDirectories(repositoryClient, parent) + File.separator + thisName;
|
||||||
} else {
|
} else {
|
||||||
path = thisName;
|
path = thisName;
|
||||||
}
|
}
|
||||||
@@ -65,10 +57,8 @@ public class RepositoryUtil {
|
|||||||
return path;
|
return path;
|
||||||
}
|
}
|
||||||
|
|
||||||
Changeset commit(String message) throws IOException {
|
static Changeset commit(RepositoryClient repositoryClient, String username, String message) throws IOException {
|
||||||
Changeset changeset = repositoryClient.getCommitCommand().commit(
|
Changeset changeset = repositoryClient.getCommitCommand().commit(new Person(username, username + "@scm-manager.org"), message);
|
||||||
new Person("scmadmin", "scmadmin@scm-manager.org"), message
|
|
||||||
);
|
|
||||||
if (repositoryClient.isCommandSupported(ClientCommand.PUSH)) {
|
if (repositoryClient.isCommandSupported(ClientCommand.PUSH)) {
|
||||||
repositoryClient.getPushCommand().push();
|
repositoryClient.getPushCommand().push();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -19,15 +19,19 @@ public class RestUtil {
|
|||||||
public static final String ADMIN_USERNAME = "scmadmin";
|
public static final String ADMIN_USERNAME = "scmadmin";
|
||||||
public static final String ADMIN_PASSWORD = "scmadmin";
|
public static final String ADMIN_PASSWORD = "scmadmin";
|
||||||
|
|
||||||
public static RequestSpecification given(String mediaType) {
|
|
||||||
return RestAssured.given()
|
|
||||||
.contentType(mediaType)
|
|
||||||
.accept(mediaType)
|
|
||||||
.auth().preemptive().basic(ADMIN_USERNAME, ADMIN_PASSWORD);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static RequestSpecification given() {
|
public static RequestSpecification given() {
|
||||||
return RestAssured.given()
|
return RestAssured.given()
|
||||||
.auth().preemptive().basic(ADMIN_USERNAME, ADMIN_PASSWORD);
|
.auth().preemptive().basic(ADMIN_USERNAME, ADMIN_PASSWORD);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public static RequestSpecification given(String mediaType) {
|
||||||
|
return given(mediaType, ADMIN_USERNAME, ADMIN_PASSWORD);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static RequestSpecification given(String mediaType, String username, String password) {
|
||||||
|
return RestAssured.given()
|
||||||
|
.contentType(mediaType)
|
||||||
|
.accept(mediaType)
|
||||||
|
.auth().preemptive().basic(username, password);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,10 @@
|
|||||||
package sonia.scm.it;
|
package sonia.scm.it;
|
||||||
|
|
||||||
|
import io.restassured.response.ValidatableResponse;
|
||||||
import org.apache.http.HttpStatus;
|
import org.apache.http.HttpStatus;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
import sonia.scm.repository.PermissionType;
|
||||||
import sonia.scm.web.VndMediaType;
|
import sonia.scm.web.VndMediaType;
|
||||||
|
|
||||||
import javax.json.Json;
|
import javax.json.Json;
|
||||||
@@ -19,7 +21,9 @@ public class TestData {
|
|||||||
|
|
||||||
private static final Logger LOG = LoggerFactory.getLogger(TestData.class);
|
private static final Logger LOG = LoggerFactory.getLogger(TestData.class);
|
||||||
|
|
||||||
private static final List<String> PROTECTED_USERS = asList("scmadmin", "anonymous");
|
public static final String USER_SCM_ADMIN = "scmadmin";
|
||||||
|
public static final String USER_ANONYMOUS = "anonymous";
|
||||||
|
private static final List<String> PROTECTED_USERS = asList(USER_SCM_ADMIN, USER_ANONYMOUS);
|
||||||
|
|
||||||
private static Map<String, String> DEFAULT_REPOSITORIES = new HashMap<>();
|
private static Map<String, String> DEFAULT_REPOSITORIES = new HashMap<>();
|
||||||
|
|
||||||
@@ -38,6 +42,77 @@ public class TestData {
|
|||||||
return DEFAULT_REPOSITORIES.get(repositoryType);
|
return DEFAULT_REPOSITORIES.get(repositoryType);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public static void createUser(String username, String password) {
|
||||||
|
given(VndMediaType.USER)
|
||||||
|
.when()
|
||||||
|
.content(" {\n" +
|
||||||
|
" \"active\": true,\n" +
|
||||||
|
" \"admin\": false,\n" +
|
||||||
|
" \"creationDate\": \"2018-08-21T12:26:46.084Z\",\n" +
|
||||||
|
" \"displayName\": \"" + username + "\",\n" +
|
||||||
|
" \"mail\": \"user1@scm-manager.org\",\n" +
|
||||||
|
" \"name\": \"" + username + "\",\n" +
|
||||||
|
" \"password\": \"" + password + "\",\n" +
|
||||||
|
" \"type\": \"xml\"\n" +
|
||||||
|
" \n" +
|
||||||
|
" }")
|
||||||
|
.post(createResourceUrl("users"))
|
||||||
|
.then()
|
||||||
|
.statusCode(HttpStatus.SC_CREATED)
|
||||||
|
;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
public static void createUserPermission(String name, PermissionType permissionType, String repositoryType) {
|
||||||
|
given(VndMediaType.PERMISSION)
|
||||||
|
.when()
|
||||||
|
.content("{\n" +
|
||||||
|
"\t\"type\": \"" + permissionType.name() + "\",\n" +
|
||||||
|
"\t\"name\": \"" + name + "\",\n" +
|
||||||
|
"\t\"groupPermission\": false\n" +
|
||||||
|
"\t\n" +
|
||||||
|
"}")
|
||||||
|
.post(TestData.getDefaultPermissionUrl(USER_SCM_ADMIN, USER_SCM_ADMIN, repositoryType))
|
||||||
|
.then()
|
||||||
|
.statusCode(HttpStatus.SC_CREATED)
|
||||||
|
;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static List<Object> getUserPermissions(String username, String password, String repositoryType) {
|
||||||
|
return callUserPermissions(username, password, repositoryType, HttpStatus.SC_OK)
|
||||||
|
.extract()
|
||||||
|
.body().jsonPath().getList("_embedded.permissions");
|
||||||
|
}
|
||||||
|
|
||||||
|
public static ValidatableResponse callUserPermissions(String username, String password, String repositoryType, int expectedStatusCode) {
|
||||||
|
return given(VndMediaType.PERMISSION, username, password)
|
||||||
|
.when()
|
||||||
|
.get(TestData.getDefaultPermissionUrl(username, password, repositoryType))
|
||||||
|
.then()
|
||||||
|
.statusCode(expectedStatusCode);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static ValidatableResponse callRepository(String username, String password, String repositoryType, int expectedStatusCode) {
|
||||||
|
return given(VndMediaType.REPOSITORY, username, password)
|
||||||
|
|
||||||
|
.when()
|
||||||
|
.get(getDefaultRepositoryUrl(repositoryType))
|
||||||
|
|
||||||
|
.then()
|
||||||
|
.statusCode(expectedStatusCode);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String getDefaultPermissionUrl(String username, String password, String repositoryType) {
|
||||||
|
return given(VndMediaType.REPOSITORY, username, password)
|
||||||
|
.when()
|
||||||
|
.get(getDefaultRepositoryUrl(repositoryType))
|
||||||
|
.then()
|
||||||
|
.statusCode(HttpStatus.SC_OK)
|
||||||
|
.extract()
|
||||||
|
.body().jsonPath().getString("_links.permissions.href");
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
private static void cleanupRepositories() {
|
private static void cleanupRepositories() {
|
||||||
List<String> repositories = given(VndMediaType.REPOSITORY_COLLECTION)
|
List<String> repositories = given(VndMediaType.REPOSITORY_COLLECTION)
|
||||||
.when()
|
.when()
|
||||||
|
|||||||
@@ -28,12 +28,6 @@
|
|||||||
<version>2.0.0-SNAPSHOT</version>
|
<version>2.0.0-SNAPSHOT</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
|
||||||
<groupId>junit</groupId>
|
|
||||||
<artifactId>junit</artifactId>
|
|
||||||
<scope>compile</scope>
|
|
||||||
</dependency>
|
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.github.sdorra</groupId>
|
<groupId>com.github.sdorra</groupId>
|
||||||
<artifactId>shiro-unit</artifactId>
|
<artifactId>shiro-unit</artifactId>
|
||||||
|
|||||||
@@ -287,7 +287,7 @@
|
|||||||
<version>${jersey-client.version}</version>
|
<version>${jersey-client.version}</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<!-- core plugins -->
|
<!-- core plugins -->
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
|
|||||||
@@ -1,30 +1,30 @@
|
|||||||
/**
|
/*
|
||||||
* Copyright (c) 2010, Sebastian Sdorra All rights reserved.
|
Copyright (c) 2010, Sebastian Sdorra All rights reserved.
|
||||||
*
|
|
||||||
* Redistribution and use in source and binary forms, with or without
|
Redistribution and use in source and binary forms, with or without
|
||||||
* modification, are permitted provided that the following conditions are met:
|
modification, are permitted provided that the following conditions are met:
|
||||||
*
|
|
||||||
* 1. Redistributions of source code must retain the above copyright notice,
|
1. Redistributions of source code must retain the above copyright notice,
|
||||||
* this list of conditions and the following disclaimer. 2. Redistributions in
|
this list of conditions and the following disclaimer. 2. Redistributions in
|
||||||
* binary form must reproduce the above copyright notice, this list of
|
binary form must reproduce the above copyright notice, this list of
|
||||||
* conditions and the following disclaimer in the documentation and/or other
|
conditions and the following disclaimer in the documentation and/or other
|
||||||
* materials provided with the distribution. 3. Neither the name of SCM-Manager;
|
materials provided with the distribution. 3. Neither the name of SCM-Manager;
|
||||||
* nor the names of its contributors may be used to endorse or promote products
|
nor the names of its contributors may be used to endorse or promote products
|
||||||
* derived from this software without specific prior written permission.
|
derived from this software without specific prior written permission.
|
||||||
*
|
|
||||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||||
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||||
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
||||||
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR
|
ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR
|
||||||
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||||
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||||
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||||
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||||
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||||
*
|
|
||||||
* http://bitbucket.org/sdorra/scm-manager
|
http://bitbucket.org/sdorra/scm-manager
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
|
||||||
@@ -36,11 +36,11 @@ package sonia.scm.api.rest;
|
|||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
//~--- JDK imports ------------------------------------------------------------
|
|
||||||
|
|
||||||
import javax.ws.rs.core.Response;
|
import javax.ws.rs.core.Response;
|
||||||
import javax.ws.rs.ext.ExceptionMapper;
|
import javax.ws.rs.ext.ExceptionMapper;
|
||||||
|
|
||||||
|
//~--- JDK imports ------------------------------------------------------------
|
||||||
|
|
||||||
/**
|
/**
|
||||||
*
|
*
|
||||||
* @author Sebastian Sdorra
|
* @author Sebastian Sdorra
|
||||||
@@ -56,14 +56,14 @@ public class StatusExceptionMapper<E extends Throwable>
|
|||||||
private static final Logger logger =
|
private static final Logger logger =
|
||||||
LoggerFactory.getLogger(StatusExceptionMapper.class);
|
LoggerFactory.getLogger(StatusExceptionMapper.class);
|
||||||
|
|
||||||
//~--- constructors ---------------------------------------------------------
|
private final Response.Status status;
|
||||||
|
private final Class<E> type;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Constructs ...
|
* Map an Exception to a HTTP Response
|
||||||
*
|
*
|
||||||
*
|
* @param type the exception class
|
||||||
* @param type
|
* @param status the http status to be mapped
|
||||||
* @param status
|
|
||||||
*/
|
*/
|
||||||
public StatusExceptionMapper(Class<E> type, Response.Status status)
|
public StatusExceptionMapper(Class<E> type, Response.Status status)
|
||||||
{
|
{
|
||||||
@@ -71,15 +71,12 @@ public class StatusExceptionMapper<E extends Throwable>
|
|||||||
this.status = status;
|
this.status = status;
|
||||||
}
|
}
|
||||||
|
|
||||||
//~--- methods --------------------------------------------------------------
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Method description
|
* provide a http responses from an exception
|
||||||
*
|
*
|
||||||
|
* @param exception the thrown exception
|
||||||
*
|
*
|
||||||
* @param exception
|
* @return the http response with the exception presentation
|
||||||
*
|
|
||||||
* @return
|
|
||||||
*/
|
*/
|
||||||
@Override
|
@Override
|
||||||
public Response toResponse(E exception)
|
public Response toResponse(E exception)
|
||||||
@@ -95,12 +92,4 @@ public class StatusExceptionMapper<E extends Throwable>
|
|||||||
|
|
||||||
return Response.status(status).build();
|
return Response.status(status).build();
|
||||||
}
|
}
|
||||||
|
|
||||||
//~--- fields ---------------------------------------------------------------
|
|
||||||
|
|
||||||
/** Field description */
|
|
||||||
private final Response.Status status;
|
|
||||||
|
|
||||||
/** Field description */
|
|
||||||
private final Class<E> type;
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -62,7 +62,7 @@ public class ContentResource {
|
|||||||
})
|
})
|
||||||
public Response get(@PathParam("namespace") String namespace, @PathParam("name") String name, @PathParam("revision") String revision, @PathParam("path") String path) {
|
public Response get(@PathParam("namespace") String namespace, @PathParam("name") String name, @PathParam("revision") String revision, @PathParam("path") String path) {
|
||||||
StreamingOutput stream = createStreamingOutput(namespace, name, revision, path);
|
StreamingOutput stream = createStreamingOutput(namespace, name, revision, path);
|
||||||
try (RepositoryService repositoryService = serviceFactory.create(new NamespaceAndName(namespace, name))) {
|
try (RepositoryService repositoryService = serviceFactory.create(new NamespaceAndName(namespace, name))) {
|
||||||
Response.ResponseBuilder responseBuilder = Response.ok(stream);
|
Response.ResponseBuilder responseBuilder = Response.ok(stream);
|
||||||
return createContentHeader(namespace, name, revision, path, repositoryService, responseBuilder);
|
return createContentHeader(namespace, name, revision, path, repositoryService, responseBuilder);
|
||||||
} catch (RepositoryNotFoundException e) {
|
} catch (RepositoryNotFoundException e) {
|
||||||
|
|||||||
@@ -25,6 +25,8 @@ public class MapperModule extends AbstractModule {
|
|||||||
bind(RepositoryTypeCollectionToDtoMapper.class);
|
bind(RepositoryTypeCollectionToDtoMapper.class);
|
||||||
|
|
||||||
bind(BranchToBranchDtoMapper.class).to(Mappers.getMapper(BranchToBranchDtoMapper.class).getClass());
|
bind(BranchToBranchDtoMapper.class).to(Mappers.getMapper(BranchToBranchDtoMapper.class).getClass());
|
||||||
|
bind(PermissionDtoToPermissionMapper.class).to(Mappers.getMapper(PermissionDtoToPermissionMapper.class).getClass());
|
||||||
|
bind(PermissionToPermissionDtoMapper.class).to(Mappers.getMapper(PermissionToPermissionDtoMapper.class).getClass());
|
||||||
|
|
||||||
bind(FileObjectToFileObjectDtoMapper.class).to(Mappers.getMapper(FileObjectToFileObjectDtoMapper.class).getClass());
|
bind(FileObjectToFileObjectDtoMapper.class).to(Mappers.getMapper(FileObjectToFileObjectDtoMapper.class).getClass());
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,49 @@
|
|||||||
|
/*
|
||||||
|
Copyright (c) 2014, Sebastian Sdorra All rights reserved.
|
||||||
|
|
||||||
|
Redistribution and use in source and binary forms, with or without
|
||||||
|
modification, are permitted provided that the following conditions are met:
|
||||||
|
|
||||||
|
1. Redistributions of source code must retain the above copyright notice,
|
||||||
|
this list of conditions and the following disclaimer. 2. Redistributions in
|
||||||
|
binary form must reproduce the above copyright notice, this list of
|
||||||
|
conditions and the following disclaimer in the documentation and/or other
|
||||||
|
materials provided with the distribution. 3. Neither the name of SCM-Manager;
|
||||||
|
nor the names of its contributors may be used to endorse or promote products
|
||||||
|
derived from this software without specific prior written permission.
|
||||||
|
|
||||||
|
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||||
|
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||||
|
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
||||||
|
ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR
|
||||||
|
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||||
|
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||||
|
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||||
|
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||||
|
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||||
|
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||||
|
|
||||||
|
http://bitbucket.org/sdorra/scm-manager
|
||||||
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
package sonia.scm.api.v2.resources;
|
||||||
|
|
||||||
|
|
||||||
|
import sonia.scm.api.rest.StatusExceptionMapper;
|
||||||
|
import sonia.scm.repository.PermissionAlreadyExistsException;
|
||||||
|
|
||||||
|
import javax.ws.rs.core.Response;
|
||||||
|
import javax.ws.rs.ext.Provider;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @since 2.0.0
|
||||||
|
*/
|
||||||
|
@Provider
|
||||||
|
public class PermissionAlreadyExistsExceptionMapper extends StatusExceptionMapper<PermissionAlreadyExistsException> {
|
||||||
|
|
||||||
|
public PermissionAlreadyExistsExceptionMapper() {
|
||||||
|
super(PermissionAlreadyExistsException.class, Response.Status.CONFLICT);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
package sonia.scm.api.v2.resources;
|
|
||||||
|
|
||||||
import javax.ws.rs.DefaultValue;
|
|
||||||
import javax.ws.rs.GET;
|
|
||||||
import javax.ws.rs.Path;
|
|
||||||
import javax.ws.rs.QueryParam;
|
|
||||||
import javax.ws.rs.core.Response;
|
|
||||||
|
|
||||||
public class PermissionCollectionResource {
|
|
||||||
@GET
|
|
||||||
@Path("")
|
|
||||||
public Response getAll(@DefaultValue("0") @QueryParam("page") int page,
|
|
||||||
@DefaultValue("10") @QueryParam("pageSize") int pageSize,
|
|
||||||
@QueryParam("sortBy") String sortBy,
|
|
||||||
@DefaultValue("false") @QueryParam("desc") boolean desc) {
|
|
||||||
throw new UnsupportedOperationException();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
package sonia.scm.api.v2.resources;
|
||||||
|
|
||||||
|
import com.google.inject.Inject;
|
||||||
|
import de.otto.edison.hal.Embedded;
|
||||||
|
import de.otto.edison.hal.HalRepresentation;
|
||||||
|
import de.otto.edison.hal.Links;
|
||||||
|
import sonia.scm.repository.Repository;
|
||||||
|
import sonia.scm.repository.RepositoryPermissions;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import static de.otto.edison.hal.Embedded.embeddedBuilder;
|
||||||
|
import static de.otto.edison.hal.Link.link;
|
||||||
|
import static de.otto.edison.hal.Links.linkingTo;
|
||||||
|
import static java.util.stream.Collectors.toList;
|
||||||
|
|
||||||
|
public class PermissionCollectionToDtoMapper {
|
||||||
|
|
||||||
|
private final ResourceLinks resourceLinks;
|
||||||
|
private final PermissionToPermissionDtoMapper permissionToPermissionDtoMapper;
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
public PermissionCollectionToDtoMapper(PermissionToPermissionDtoMapper permissionToPermissionDtoMapper, ResourceLinks resourceLinks) {
|
||||||
|
this.resourceLinks = resourceLinks;
|
||||||
|
this.permissionToPermissionDtoMapper = permissionToPermissionDtoMapper;
|
||||||
|
}
|
||||||
|
|
||||||
|
public HalRepresentation map(Repository repository) {
|
||||||
|
List<PermissionDto> permissionDtoList = repository.getPermissions()
|
||||||
|
.stream()
|
||||||
|
.map(permission -> permissionToPermissionDtoMapper.map(permission, repository))
|
||||||
|
.collect(toList());
|
||||||
|
return new HalRepresentation(createLinks(repository), embedDtos(permissionDtoList));
|
||||||
|
}
|
||||||
|
|
||||||
|
private Links createLinks(Repository repository) {
|
||||||
|
RepositoryPermissions.permissionRead(repository).check();
|
||||||
|
Links.Builder linksBuilder = linkingTo()
|
||||||
|
.with(Links.linkingTo().self(resourceLinks.permission().all(repository.getNamespace(), repository.getName())).build());
|
||||||
|
if (RepositoryPermissions.permissionWrite(repository).isPermitted()) {
|
||||||
|
linksBuilder.single(link("create", resourceLinks.permission().create(repository.getNamespace(), repository.getName())));
|
||||||
|
}
|
||||||
|
return linksBuilder.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
private Embedded embedDtos(List<PermissionDto> permissionDtoList) {
|
||||||
|
return embeddedBuilder()
|
||||||
|
.with("permissions", permissionDtoList)
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
package sonia.scm.api.v2.resources;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||||
|
import de.otto.edison.hal.HalRepresentation;
|
||||||
|
import de.otto.edison.hal.Links;
|
||||||
|
import lombok.Getter;
|
||||||
|
import lombok.Setter;
|
||||||
|
import lombok.ToString;
|
||||||
|
|
||||||
|
@Getter @Setter @ToString
|
||||||
|
public class PermissionDto extends HalRepresentation {
|
||||||
|
|
||||||
|
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* the type can be replaced with a dto enum if the mapstruct 1.3.0 is stable
|
||||||
|
* the mapstruct has a Bug on mapping enums in the 1.2.0-Final Version
|
||||||
|
*
|
||||||
|
* see the bug fix: https://github.com/mapstruct/mapstruct/commit/460e87eef6eb71245b387fdb0509c726676a8e19
|
||||||
|
*
|
||||||
|
**/
|
||||||
|
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||||
|
private String type ;
|
||||||
|
|
||||||
|
|
||||||
|
private boolean groupPermission = false;
|
||||||
|
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@SuppressWarnings("squid:S1185") // We want to have this method available in this package
|
||||||
|
protected HalRepresentation add(Links links) {
|
||||||
|
return super.add(links);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
package sonia.scm.api.v2.resources;
|
||||||
|
|
||||||
|
import org.mapstruct.Mapper;
|
||||||
|
import org.mapstruct.MappingTarget;
|
||||||
|
import sonia.scm.repository.Permission;
|
||||||
|
|
||||||
|
@Mapper
|
||||||
|
public abstract class PermissionDtoToPermissionMapper {
|
||||||
|
|
||||||
|
public abstract Permission map(PermissionDto permissionDto);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* this method is needed to modify an existing permission object
|
||||||
|
*
|
||||||
|
* @param target the target permission
|
||||||
|
* @param permissionDto the source dto
|
||||||
|
* @return the mapped target permission object
|
||||||
|
*/
|
||||||
|
public abstract void modify(@MappingTarget Permission target, PermissionDto permissionDto);
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
/*
|
||||||
|
Copyright (c) 2014, Sebastian Sdorra All rights reserved.
|
||||||
|
|
||||||
|
Redistribution and use in source and binary forms, with or without
|
||||||
|
modification, are permitted provided that the following conditions are met:
|
||||||
|
|
||||||
|
1. Redistributions of source code must retain the above copyright notice,
|
||||||
|
this list of conditions and the following disclaimer. 2. Redistributions in
|
||||||
|
binary form must reproduce the above copyright notice, this list of
|
||||||
|
conditions and the following disclaimer in the documentation and/or other
|
||||||
|
materials provided with the distribution. 3. Neither the name of SCM-Manager;
|
||||||
|
nor the names of its contributors may be used to endorse or promote products
|
||||||
|
derived from this software without specific prior written permission.
|
||||||
|
|
||||||
|
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||||
|
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||||
|
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
||||||
|
ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR
|
||||||
|
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||||
|
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||||
|
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||||
|
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||||
|
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||||
|
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||||
|
|
||||||
|
http://bitbucket.org/sdorra/scm-manager
|
||||||
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
package sonia.scm.api.v2.resources;
|
||||||
|
|
||||||
|
|
||||||
|
import sonia.scm.api.rest.StatusExceptionMapper;
|
||||||
|
import sonia.scm.repository.PermissionNotFoundException;
|
||||||
|
|
||||||
|
import javax.ws.rs.core.Response;
|
||||||
|
import javax.ws.rs.ext.Provider;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @since 2.0.0
|
||||||
|
*/
|
||||||
|
@Provider
|
||||||
|
public class PermissionNotFoundExceptionMapper extends StatusExceptionMapper<PermissionNotFoundException> {
|
||||||
|
|
||||||
|
public PermissionNotFoundExceptionMapper() {
|
||||||
|
super(PermissionNotFoundException.class, Response.Status.NOT_FOUND);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,20 +1,235 @@
|
|||||||
package sonia.scm.api.v2.resources;
|
package sonia.scm.api.v2.resources;
|
||||||
|
|
||||||
import javax.inject.Inject;
|
import com.webcohesion.enunciate.metadata.rs.ResponseCode;
|
||||||
import javax.inject.Provider;
|
import com.webcohesion.enunciate.metadata.rs.ResponseHeader;
|
||||||
import javax.ws.rs.Path;
|
import com.webcohesion.enunciate.metadata.rs.StatusCodes;
|
||||||
|
import com.webcohesion.enunciate.metadata.rs.TypeHint;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.apache.commons.lang.StringUtils;
|
||||||
|
import sonia.scm.repository.NamespaceAndName;
|
||||||
|
import sonia.scm.repository.Permission;
|
||||||
|
import sonia.scm.repository.PermissionAlreadyExistsException;
|
||||||
|
import sonia.scm.repository.PermissionNotFoundException;
|
||||||
|
import sonia.scm.repository.Repository;
|
||||||
|
import sonia.scm.repository.RepositoryException;
|
||||||
|
import sonia.scm.repository.RepositoryManager;
|
||||||
|
import sonia.scm.repository.RepositoryNotFoundException;
|
||||||
|
import sonia.scm.repository.RepositoryPermissions;
|
||||||
|
import sonia.scm.web.VndMediaType;
|
||||||
|
|
||||||
|
import javax.inject.Inject;
|
||||||
|
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;
|
||||||
|
import javax.ws.rs.Produces;
|
||||||
|
import javax.ws.rs.core.Response;
|
||||||
|
import java.net.URI;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
@Slf4j
|
||||||
public class PermissionRootResource {
|
public class PermissionRootResource {
|
||||||
|
|
||||||
private final Provider<PermissionCollectionResource> permissionCollectionResource;
|
private PermissionDtoToPermissionMapper dtoToModelMapper;
|
||||||
|
private PermissionToPermissionDtoMapper modelToDtoMapper;
|
||||||
|
private PermissionCollectionToDtoMapper permissionCollectionToDtoMapper;
|
||||||
|
private ResourceLinks resourceLinks;
|
||||||
|
private final RepositoryManager manager;
|
||||||
|
|
||||||
|
|
||||||
@Inject
|
@Inject
|
||||||
public PermissionRootResource(Provider<PermissionCollectionResource> permissionCollectionResource) {
|
public PermissionRootResource(PermissionDtoToPermissionMapper dtoToModelMapper, PermissionToPermissionDtoMapper modelToDtoMapper, PermissionCollectionToDtoMapper permissionCollectionToDtoMapper, ResourceLinks resourceLinks, RepositoryManager manager) {
|
||||||
this.permissionCollectionResource = permissionCollectionResource;
|
this.dtoToModelMapper = dtoToModelMapper;
|
||||||
|
this.modelToDtoMapper = modelToDtoMapper;
|
||||||
|
this.permissionCollectionToDtoMapper = permissionCollectionToDtoMapper;
|
||||||
|
this.resourceLinks = resourceLinks;
|
||||||
|
this.manager = manager;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Adds a new permission to the user or group managed by the repository
|
||||||
|
*
|
||||||
|
* @param permission permission to add
|
||||||
|
* @return a web response with the status code 201 and the url to GET the added permission
|
||||||
|
*/
|
||||||
|
@POST
|
||||||
|
@StatusCodes({
|
||||||
|
@ResponseCode(code = 201, condition = "creates", additionalHeaders = {
|
||||||
|
@ResponseHeader(name = "Location", description = "uri of the created permission")
|
||||||
|
}),
|
||||||
|
@ResponseCode(code = 500, condition = "internal server error"),
|
||||||
|
@ResponseCode(code = 404, condition = "not found"),
|
||||||
|
@ResponseCode(code = 409, condition = "conflict")
|
||||||
|
})
|
||||||
|
@TypeHint(TypeHint.NO_CONTENT.class)
|
||||||
|
@Consumes(VndMediaType.PERMISSION)
|
||||||
@Path("")
|
@Path("")
|
||||||
public PermissionCollectionResource getPermissionCollectionResource() {
|
public Response create(@PathParam("namespace") String namespace, @PathParam("name") String name, PermissionDto permission) throws RepositoryException {
|
||||||
return permissionCollectionResource.get();
|
log.info("try to add new permission: {}", permission);
|
||||||
|
Repository repository = load(namespace, name);
|
||||||
|
RepositoryPermissions.permissionWrite(repository).check();
|
||||||
|
checkPermissionAlreadyExists(permission, repository);
|
||||||
|
repository.getPermissions().add(dtoToModelMapper.map(permission));
|
||||||
|
manager.modify(repository);
|
||||||
|
return Response.created(URI.create(resourceLinks.permission().self(namespace, name, permission.getName()))).build();
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the searched permission with permission name related to a repository
|
||||||
|
*
|
||||||
|
* @param namespace the repository namespace
|
||||||
|
* @param name the repository name
|
||||||
|
* @return the http response with a list of permissionDto objects
|
||||||
|
* @throws RepositoryNotFoundException if the repository does not exists
|
||||||
|
*/
|
||||||
|
@GET
|
||||||
|
@StatusCodes({
|
||||||
|
@ResponseCode(code = 200, condition = "ok"),
|
||||||
|
@ResponseCode(code = 404, condition = "not found"),
|
||||||
|
@ResponseCode(code = 500, condition = "internal server error")
|
||||||
|
})
|
||||||
|
@Produces(VndMediaType.PERMISSION)
|
||||||
|
@TypeHint(PermissionDto.class)
|
||||||
|
@Path("{permission-name}")
|
||||||
|
public Response get(@PathParam("namespace") String namespace, @PathParam("name") String name, @PathParam("permission-name") String permissionName) throws RepositoryException {
|
||||||
|
Repository repository = load(namespace, name);
|
||||||
|
RepositoryPermissions.permissionRead(repository).check();
|
||||||
|
return Response.ok(
|
||||||
|
repository.getPermissions()
|
||||||
|
.stream()
|
||||||
|
.filter(permission -> permissionName.equals(permission.getName()))
|
||||||
|
.map(permission -> modelToDtoMapper.map(permission, repository))
|
||||||
|
.findFirst()
|
||||||
|
.orElseThrow(() -> new PermissionNotFoundException(repository, permissionName))
|
||||||
|
).build();
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get all permissions related to a repository
|
||||||
|
*
|
||||||
|
* @param namespace the repository namespace
|
||||||
|
* @param name the repository name
|
||||||
|
* @return the http response with a list of permissionDto objects
|
||||||
|
* @throws RepositoryNotFoundException if the repository does not exists
|
||||||
|
*/
|
||||||
|
@GET
|
||||||
|
@StatusCodes({
|
||||||
|
@ResponseCode(code = 200, condition = "ok"),
|
||||||
|
@ResponseCode(code = 404, condition = "not found"),
|
||||||
|
@ResponseCode(code = 500, condition = "internal server error")
|
||||||
|
})
|
||||||
|
@Produces(VndMediaType.PERMISSION)
|
||||||
|
@TypeHint(PermissionDto.class)
|
||||||
|
@Path("")
|
||||||
|
public Response getAll(@PathParam("namespace") String namespace, @PathParam("name") String name) throws RepositoryNotFoundException {
|
||||||
|
Repository repository = load(namespace, name);
|
||||||
|
RepositoryPermissions.permissionRead(repository).check();
|
||||||
|
return Response.ok(permissionCollectionToDtoMapper.map(repository)).build();
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Update a permission to the user or group managed by the repository
|
||||||
|
*
|
||||||
|
* @param permission permission to modify
|
||||||
|
* @param permissionName permission to modify
|
||||||
|
* @return a web response with the status code 204
|
||||||
|
*/
|
||||||
|
@PUT
|
||||||
|
@StatusCodes({
|
||||||
|
@ResponseCode(code = 204, condition = "update success"),
|
||||||
|
@ResponseCode(code = 401, condition = "not authenticated / invalid credentials"),
|
||||||
|
@ResponseCode(code = 500, condition = "internal server error")
|
||||||
|
})
|
||||||
|
@TypeHint(TypeHint.NO_CONTENT.class)
|
||||||
|
@Consumes(VndMediaType.PERMISSION)
|
||||||
|
@Path("{permission-name}")
|
||||||
|
public Response update(@PathParam("namespace") String namespace,
|
||||||
|
@PathParam("name") String name,
|
||||||
|
@PathParam("permission-name") String permissionName,
|
||||||
|
PermissionDto permission) throws RepositoryException {
|
||||||
|
log.info("try to update the permission with name: {}. the modified permission is: {}", permissionName, permission);
|
||||||
|
Repository repository = load(namespace, name);
|
||||||
|
RepositoryPermissions.permissionWrite(repository).check();
|
||||||
|
Permission existingPermission = repository.getPermissions()
|
||||||
|
.stream()
|
||||||
|
.filter(perm -> StringUtils.isNotBlank(perm.getName()) && perm.getName().equals(permissionName))
|
||||||
|
.findFirst()
|
||||||
|
.orElseThrow(() -> new PermissionNotFoundException(repository, permissionName));
|
||||||
|
dtoToModelMapper.modify(existingPermission, permission);
|
||||||
|
manager.modify(repository);
|
||||||
|
log.info("the permission with name: {} is updated.", permissionName);
|
||||||
|
return Response.noContent().build();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Update a permission to the user or group managed by the repository
|
||||||
|
*
|
||||||
|
* @param permissionName permission to delete
|
||||||
|
* @return a web response with the status code 204
|
||||||
|
*/
|
||||||
|
@DELETE
|
||||||
|
@StatusCodes({
|
||||||
|
@ResponseCode(code = 204, condition = "delete success or nothing to delete"),
|
||||||
|
@ResponseCode(code = 401, condition = "not authenticated / invalid credentials"),
|
||||||
|
@ResponseCode(code = 403, condition = "not authorized"),
|
||||||
|
@ResponseCode(code = 500, condition = "internal server error")
|
||||||
|
})
|
||||||
|
@TypeHint(TypeHint.NO_CONTENT.class)
|
||||||
|
@Path("{permission-name}")
|
||||||
|
public Response delete(@PathParam("namespace") String namespace,
|
||||||
|
@PathParam("name") String name,
|
||||||
|
@PathParam("permission-name") String permissionName) throws RepositoryException {
|
||||||
|
log.info("try to delete the permission with name: {}.", permissionName);
|
||||||
|
Repository repository = load(namespace, name);
|
||||||
|
RepositoryPermissions.modify(repository).check();
|
||||||
|
repository.getPermissions()
|
||||||
|
.stream()
|
||||||
|
.filter(perm -> StringUtils.isNotBlank(perm.getName()) && perm.getName().equals(permissionName))
|
||||||
|
.findFirst()
|
||||||
|
.ifPresent(p -> repository.getPermissions().remove(p))
|
||||||
|
;
|
||||||
|
manager.modify(repository);
|
||||||
|
log.info("the permission with name: {} is updated.", permissionName);
|
||||||
|
return Response.noContent().build();
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* check if the actual user is permitted to manage the repository permissions
|
||||||
|
* return the repository if the user is permitted
|
||||||
|
*
|
||||||
|
* @param namespace the repository namespace
|
||||||
|
* @param name the repository name
|
||||||
|
* @return the repository if the user is permitted
|
||||||
|
* @throws RepositoryNotFoundException if the repository does not exists
|
||||||
|
*/
|
||||||
|
private Repository load(String namespace, String name) throws RepositoryNotFoundException {
|
||||||
|
return Optional.ofNullable(manager.get(new NamespaceAndName(namespace, name)))
|
||||||
|
.orElseThrow(() -> new RepositoryNotFoundException(name));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* check if the permission already exists in the repository
|
||||||
|
*
|
||||||
|
* @param permission the searched permission
|
||||||
|
* @param repository the repository to be inspected
|
||||||
|
* @throws PermissionAlreadyExistsException if the permission already exists in the repository
|
||||||
|
*/
|
||||||
|
private void checkPermissionAlreadyExists(PermissionDto permission, Repository repository) throws PermissionAlreadyExistsException {
|
||||||
|
boolean isPermissionAlreadyExist = repository.getPermissions()
|
||||||
|
.stream()
|
||||||
|
.anyMatch(p -> p.getName().equals(permission.getName()));
|
||||||
|
if (isPermissionAlreadyExist) {
|
||||||
|
throw new PermissionAlreadyExistsException(repository, permission.getName());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,51 @@
|
|||||||
|
package sonia.scm.api.v2.resources;
|
||||||
|
|
||||||
|
import de.otto.edison.hal.Links;
|
||||||
|
import org.mapstruct.AfterMapping;
|
||||||
|
import org.mapstruct.BeforeMapping;
|
||||||
|
import org.mapstruct.Context;
|
||||||
|
import org.mapstruct.Mapper;
|
||||||
|
import org.mapstruct.Mapping;
|
||||||
|
import org.mapstruct.MappingTarget;
|
||||||
|
import sonia.scm.repository.Permission;
|
||||||
|
import sonia.scm.repository.Repository;
|
||||||
|
import sonia.scm.repository.RepositoryPermissions;
|
||||||
|
|
||||||
|
import javax.inject.Inject;
|
||||||
|
|
||||||
|
import static de.otto.edison.hal.Link.link;
|
||||||
|
import static de.otto.edison.hal.Links.linkingTo;
|
||||||
|
|
||||||
|
@Mapper
|
||||||
|
public abstract class PermissionToPermissionDtoMapper {
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
private ResourceLinks resourceLinks;
|
||||||
|
|
||||||
|
@Mapping(target = "attributes", ignore = true) // We do not map HAL attributes
|
||||||
|
public abstract PermissionDto map(Permission permission, @Context Repository repository);
|
||||||
|
|
||||||
|
|
||||||
|
@BeforeMapping
|
||||||
|
void validatePermissions(@Context Repository repository) {
|
||||||
|
RepositoryPermissions.permissionRead(repository).check();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add the self, update and delete links.
|
||||||
|
*
|
||||||
|
* @param target the mapped dto
|
||||||
|
* @param repository the repository
|
||||||
|
*/
|
||||||
|
@AfterMapping
|
||||||
|
void appendLinks(@MappingTarget PermissionDto target, @Context Repository repository) {
|
||||||
|
Links.Builder linksBuilder = linkingTo()
|
||||||
|
.self(resourceLinks.permission().self(repository.getNamespace(), repository.getName(), target.getName()));
|
||||||
|
if (RepositoryPermissions.permissionWrite(repository).isPermitted()) {
|
||||||
|
linksBuilder.single(link("update", resourceLinks.permission().update(repository.getNamespace(), repository.getName(), target.getName())));
|
||||||
|
linksBuilder.single(link("delete", resourceLinks.permission().delete(repository.getNamespace(), repository.getName(), target.getName())));
|
||||||
|
}
|
||||||
|
target.add(linksBuilder.build());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
/*
|
||||||
|
Copyright (c) 2014, Sebastian Sdorra All rights reserved.
|
||||||
|
|
||||||
|
Redistribution and use in source and binary forms, with or without
|
||||||
|
modification, are permitted provided that the following conditions are met:
|
||||||
|
|
||||||
|
1. Redistributions of source code must retain the above copyright notice,
|
||||||
|
this list of conditions and the following disclaimer. 2. Redistributions in
|
||||||
|
binary form must reproduce the above copyright notice, this list of
|
||||||
|
conditions and the following disclaimer in the documentation and/or other
|
||||||
|
materials provided with the distribution. 3. Neither the name of SCM-Manager;
|
||||||
|
nor the names of its contributors may be used to endorse or promote products
|
||||||
|
derived from this software without specific prior written permission.
|
||||||
|
|
||||||
|
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||||
|
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||||
|
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
||||||
|
ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR
|
||||||
|
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||||
|
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||||
|
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||||
|
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||||
|
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||||
|
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||||
|
|
||||||
|
http://bitbucket.org/sdorra/scm-manager
|
||||||
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
package sonia.scm.api.v2.resources;
|
||||||
|
|
||||||
|
|
||||||
|
import sonia.scm.api.rest.StatusExceptionMapper;
|
||||||
|
import sonia.scm.repository.RepositoryNotFoundException;
|
||||||
|
|
||||||
|
import javax.ws.rs.core.Response;
|
||||||
|
import javax.ws.rs.ext.Provider;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @since 2.0.0
|
||||||
|
*/
|
||||||
|
@Provider
|
||||||
|
public class RepositoryNotFoundExceptionMapper extends StatusExceptionMapper<RepositoryNotFoundException> {
|
||||||
|
|
||||||
|
public RepositoryNotFoundExceptionMapper() {
|
||||||
|
super(RepositoryNotFoundException.class, Response.Status.NOT_FOUND);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -128,11 +128,17 @@ public class RepositoryResource {
|
|||||||
public Response update(@PathParam("namespace") String namespace, @PathParam("name") String name, RepositoryDto repositoryDto) {
|
public Response update(@PathParam("namespace") String namespace, @PathParam("name") String name, RepositoryDto repositoryDto) {
|
||||||
return adapter.update(
|
return adapter.update(
|
||||||
loadBy(namespace, name),
|
loadBy(namespace, name),
|
||||||
existing -> dtoToRepositoryMapper.map(repositoryDto, existing.getId()),
|
existing -> processUpdate(repositoryDto, existing),
|
||||||
nameAndNamespaceStaysTheSame(namespace, name)
|
nameAndNamespaceStaysTheSame(namespace, name)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private Repository processUpdate(RepositoryDto repositoryDto, Repository existing) {
|
||||||
|
Repository changedRepository = dtoToRepositoryMapper.map(repositoryDto, existing.getId());
|
||||||
|
changedRepository.setPermissions(existing.getPermissions());
|
||||||
|
return changedRepository;
|
||||||
|
}
|
||||||
|
|
||||||
@Path("tags/")
|
@Path("tags/")
|
||||||
public TagRootResource tags() {
|
public TagRootResource tags() {
|
||||||
return tagRootResource.get();
|
return tagRootResource.get();
|
||||||
@@ -176,6 +182,6 @@ public class RepositoryResource {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private Predicate<Repository> nameAndNamespaceStaysTheSame(String namespace, String name) {
|
private Predicate<Repository> nameAndNamespaceStaysTheSame(String namespace, String name) {
|
||||||
return changed -> changed.getName().equals(name) && changed.getNamespace().equals(namespace);
|
return changed -> name.equals(changed.getName()) && namespace.equals(changed.getNamespace());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -36,7 +36,7 @@ public abstract class RepositoryToRepositoryDtoMapper extends BaseMapper<Reposit
|
|||||||
}
|
}
|
||||||
if (RepositoryPermissions.modify(repository).isPermitted()) {
|
if (RepositoryPermissions.modify(repository).isPermitted()) {
|
||||||
linksBuilder.single(link("update", resourceLinks.repository().update(target.getNamespace(), target.getName())));
|
linksBuilder.single(link("update", resourceLinks.repository().update(target.getNamespace(), target.getName())));
|
||||||
linksBuilder.single(link("permissions", resourceLinks.permissionCollection().self(target.getNamespace(), target.getName())));
|
linksBuilder.single(link("permissions", resourceLinks.permission().all(target.getNamespace(), target.getName())));
|
||||||
}
|
}
|
||||||
try (RepositoryService repositoryService = serviceFactory.create(repository)) {
|
try (RepositoryService repositoryService = serviceFactory.create(repository)) {
|
||||||
if (repositoryService.isSupported(Command.TAGS)) {
|
if (repositoryService.isSupported(Command.TAGS)) {
|
||||||
|
|||||||
@@ -314,20 +314,39 @@ class ResourceLinks {
|
|||||||
return sourceLinkBuilder.method("getRepositoryResource").parameters(namespace, name).method("content").parameters().method("get").parameters(revision, path).href();
|
return sourceLinkBuilder.method("getRepositoryResource").parameters(namespace, name).method("content").parameters().method("get").parameters(revision, path).href();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
public PermissionLinks permission() {
|
||||||
public PermissionCollectionLinks permissionCollection() {
|
return new PermissionLinks(uriInfoStore.get());
|
||||||
return new PermissionCollectionLinks(uriInfoStore.get());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
static class PermissionCollectionLinks {
|
static class PermissionLinks {
|
||||||
private final LinkBuilder permissionLinkBuilder;
|
private final LinkBuilder permissionLinkBuilder;
|
||||||
|
|
||||||
PermissionCollectionLinks(UriInfo uriInfo) {
|
PermissionLinks(UriInfo uriInfo) {
|
||||||
permissionLinkBuilder = new LinkBuilder(uriInfo, RepositoryRootResource.class, RepositoryResource.class, PermissionRootResource.class, PermissionCollectionResource.class);
|
permissionLinkBuilder = new LinkBuilder(uriInfo, RepositoryRootResource.class, RepositoryResource.class, PermissionRootResource.class);
|
||||||
}
|
}
|
||||||
|
|
||||||
String self(String namespace, String name) {
|
String all(String namespace, String name) {
|
||||||
return permissionLinkBuilder.method("getRepositoryResource").parameters(namespace, name).method("permissions").parameters().method("getPermissionCollectionResource").parameters().method("getAll").parameters().href();
|
return permissionLinkBuilder.method("getRepositoryResource").parameters(namespace, name).method("permissions").parameters().method("getAll").parameters().href();
|
||||||
|
}
|
||||||
|
|
||||||
|
String create(String repositoryNamespace, String repositoryName) {
|
||||||
|
return permissionLinkBuilder.method("getRepositoryResource").parameters(repositoryNamespace, repositoryName).method("permissions").parameters().method("create").parameters().href();
|
||||||
|
}
|
||||||
|
|
||||||
|
String self(String repositoryNamespace, String repositoryName, String permissionName) {
|
||||||
|
return getLink(repositoryNamespace, repositoryName, permissionName, "get");
|
||||||
|
}
|
||||||
|
|
||||||
|
String update(String repositoryNamespace, String repositoryName, String permissionName) {
|
||||||
|
return getLink(repositoryNamespace, repositoryName, permissionName, "update");
|
||||||
|
}
|
||||||
|
|
||||||
|
String delete(String repositoryNamespace, String repositoryName, String permissionName) {
|
||||||
|
return getLink(repositoryNamespace, repositoryName, permissionName, "delete");
|
||||||
|
}
|
||||||
|
|
||||||
|
private String getLink(String repositoryNamespace, String repositoryName, String permissionName, String methodName) {
|
||||||
|
return permissionLinkBuilder.method("getRepositoryResource").parameters(repositoryNamespace, repositoryName).method("permissions").parameters().method(methodName).parameters(permissionName).href();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -36,23 +36,19 @@ package sonia.scm.security;
|
|||||||
//~--- non-JDK imports --------------------------------------------------------
|
//~--- non-JDK imports --------------------------------------------------------
|
||||||
|
|
||||||
import com.github.legman.Subscribe;
|
import com.github.legman.Subscribe;
|
||||||
|
|
||||||
import com.google.common.base.Objects;
|
import com.google.common.base.Objects;
|
||||||
import com.google.common.base.Preconditions;
|
import com.google.common.base.Preconditions;
|
||||||
import com.google.common.collect.ImmutableSet;
|
import com.google.common.collect.ImmutableSet;
|
||||||
import com.google.common.collect.ImmutableSet.Builder;
|
import com.google.common.collect.ImmutableSet.Builder;
|
||||||
import com.google.inject.Inject;
|
import com.google.inject.Inject;
|
||||||
import com.google.inject.Singleton;
|
import com.google.inject.Singleton;
|
||||||
|
|
||||||
import org.apache.shiro.SecurityUtils;
|
import org.apache.shiro.SecurityUtils;
|
||||||
import org.apache.shiro.authz.AuthorizationInfo;
|
import org.apache.shiro.authz.AuthorizationInfo;
|
||||||
import org.apache.shiro.authz.SimpleAuthorizationInfo;
|
import org.apache.shiro.authz.SimpleAuthorizationInfo;
|
||||||
import org.apache.shiro.subject.PrincipalCollection;
|
import org.apache.shiro.subject.PrincipalCollection;
|
||||||
import org.apache.shiro.subject.Subject;
|
import org.apache.shiro.subject.Subject;
|
||||||
|
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
import sonia.scm.cache.Cache;
|
import sonia.scm.cache.Cache;
|
||||||
import sonia.scm.cache.CacheManager;
|
import sonia.scm.cache.CacheManager;
|
||||||
import sonia.scm.group.GroupNames;
|
import sonia.scm.group.GroupNames;
|
||||||
@@ -62,11 +58,11 @@ import sonia.scm.repository.RepositoryDAO;
|
|||||||
import sonia.scm.user.User;
|
import sonia.scm.user.User;
|
||||||
import sonia.scm.util.Util;
|
import sonia.scm.util.Util;
|
||||||
|
|
||||||
//~--- JDK imports ------------------------------------------------------------
|
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
|
|
||||||
|
//~--- JDK imports ------------------------------------------------------------
|
||||||
|
|
||||||
/**
|
/**
|
||||||
*
|
*
|
||||||
* @author Sebastian Sdorra
|
* @author Sebastian Sdorra
|
||||||
@@ -207,9 +203,9 @@ public class DefaultAuthorizationCollector implements AuthorizationCollector
|
|||||||
boolean hasPermission = false;
|
boolean hasPermission = false;
|
||||||
for (sonia.scm.repository.Permission permission : repositoryPermissions)
|
for (sonia.scm.repository.Permission permission : repositoryPermissions)
|
||||||
{
|
{
|
||||||
if (isUserPermitted(user, groups, permission))
|
hasPermission = isUserPermitted(user, groups, permission);
|
||||||
|
if (hasPermission)
|
||||||
{
|
{
|
||||||
|
|
||||||
String perm = permission.getType().getPermissionPrefix().concat(repository.getId());
|
String perm = permission.getType().getPermissionPrefix().concat(repository.getId());
|
||||||
if (logger.isTraceEnabled())
|
if (logger.isTraceEnabled())
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import org.apache.shiro.subject.Subject;
|
|||||||
import org.apache.shiro.subject.support.SubjectThreadState;
|
import org.apache.shiro.subject.support.SubjectThreadState;
|
||||||
import org.apache.shiro.util.ThreadContext;
|
import org.apache.shiro.util.ThreadContext;
|
||||||
import org.apache.shiro.util.ThreadState;
|
import org.apache.shiro.util.ThreadState;
|
||||||
|
import org.junit.After;
|
||||||
import org.junit.Before;
|
import org.junit.Before;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
import org.mockito.InjectMocks;
|
import org.mockito.InjectMocks;
|
||||||
@@ -61,6 +62,11 @@ public class BrowserResultToBrowserResultDtoMapperTest {
|
|||||||
fileObject2.setDirectory(true);
|
fileObject2.setDirectory(true);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@After
|
||||||
|
public void unbind() {
|
||||||
|
ThreadContext.unbindSubject();
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void shouldMapAttributesCorrectly() {
|
public void shouldMapAttributesCorrectly() {
|
||||||
BrowserResult browserResult = createBrowserResult();
|
BrowserResult browserResult = createBrowserResult();
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package sonia.scm.api.v2.resources;
|
|||||||
import com.github.sdorra.shiro.ShiroRule;
|
import com.github.sdorra.shiro.ShiroRule;
|
||||||
import com.github.sdorra.shiro.SubjectAware;
|
import com.github.sdorra.shiro.SubjectAware;
|
||||||
import com.google.common.io.Resources;
|
import com.google.common.io.Resources;
|
||||||
|
import org.apache.shiro.util.ThreadContext;
|
||||||
import org.jboss.resteasy.core.Dispatcher;
|
import org.jboss.resteasy.core.Dispatcher;
|
||||||
import org.jboss.resteasy.mock.MockDispatcherFactory;
|
import org.jboss.resteasy.mock.MockDispatcherFactory;
|
||||||
import org.jboss.resteasy.mock.MockHttpRequest;
|
import org.jboss.resteasy.mock.MockHttpRequest;
|
||||||
@@ -21,7 +22,9 @@ import java.net.URI;
|
|||||||
import java.net.URISyntaxException;
|
import java.net.URISyntaxException;
|
||||||
import java.net.URL;
|
import java.net.URL;
|
||||||
|
|
||||||
import static org.junit.Assert.*;
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertFalse;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
import static org.mockito.MockitoAnnotations.initMocks;
|
import static org.mockito.MockitoAnnotations.initMocks;
|
||||||
|
|
||||||
@SubjectAware(
|
@SubjectAware(
|
||||||
@@ -47,6 +50,13 @@ public class ConfigResourceTest {
|
|||||||
@InjectMocks
|
@InjectMocks
|
||||||
private ScmConfigurationToConfigDtoMapperImpl configToDtoMapper;
|
private ScmConfigurationToConfigDtoMapperImpl configToDtoMapper;
|
||||||
|
|
||||||
|
public ConfigResourceTest() {
|
||||||
|
// cleanup state that might have been left by other tests
|
||||||
|
ThreadContext.unbindSecurityManager();
|
||||||
|
ThreadContext.unbindSubject();
|
||||||
|
ThreadContext.remove();
|
||||||
|
}
|
||||||
|
|
||||||
@Before
|
@Before
|
||||||
public void prepareEnvironment() {
|
public void prepareEnvironment() {
|
||||||
initMocks(this);
|
initMocks(this);
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import org.apache.shiro.subject.Subject;
|
|||||||
import org.apache.shiro.subject.support.SubjectThreadState;
|
import org.apache.shiro.subject.support.SubjectThreadState;
|
||||||
import org.apache.shiro.util.ThreadContext;
|
import org.apache.shiro.util.ThreadContext;
|
||||||
import org.apache.shiro.util.ThreadState;
|
import org.apache.shiro.util.ThreadState;
|
||||||
|
import org.junit.After;
|
||||||
import org.junit.Before;
|
import org.junit.Before;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
import org.junit.runner.RunWith;
|
import org.junit.runner.RunWith;
|
||||||
@@ -40,6 +41,10 @@ public class FileObjectToFileObjectDtoMapperTest {
|
|||||||
ThreadContext.bind(subject);
|
ThreadContext.bind(subject);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@After
|
||||||
|
public void unbind() {
|
||||||
|
ThreadContext.unbindSubject();
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void shouldMapAttributesCorrectly() {
|
public void shouldMapAttributesCorrectly() {
|
||||||
|
|||||||
@@ -0,0 +1,460 @@
|
|||||||
|
package sonia.scm.api.v2.resources;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import com.github.sdorra.shiro.ShiroRule;
|
||||||
|
import com.github.sdorra.shiro.SubjectAware;
|
||||||
|
import com.google.common.collect.ImmutableList;
|
||||||
|
import de.otto.edison.hal.HalRepresentation;
|
||||||
|
import lombok.ToString;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.apache.shiro.authz.AuthorizationException;
|
||||||
|
import org.apache.shiro.subject.Subject;
|
||||||
|
import org.apache.shiro.subject.support.SubjectThreadState;
|
||||||
|
import org.apache.shiro.util.ThreadContext;
|
||||||
|
import org.apache.shiro.util.ThreadState;
|
||||||
|
import org.assertj.core.util.Lists;
|
||||||
|
import org.jboss.resteasy.core.Dispatcher;
|
||||||
|
import org.jboss.resteasy.mock.MockDispatcherFactory;
|
||||||
|
import org.jboss.resteasy.mock.MockHttpRequest;
|
||||||
|
import org.jboss.resteasy.mock.MockHttpResponse;
|
||||||
|
import org.jboss.resteasy.spi.HttpRequest;
|
||||||
|
import org.junit.After;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Rule;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.DisplayName;
|
||||||
|
import org.junit.jupiter.api.DynamicTest;
|
||||||
|
import org.junit.jupiter.api.TestFactory;
|
||||||
|
import org.mockito.InjectMocks;
|
||||||
|
import org.mockito.Mock;
|
||||||
|
import sonia.scm.api.rest.AuthorizationExceptionMapper;
|
||||||
|
import sonia.scm.repository.NamespaceAndName;
|
||||||
|
import sonia.scm.repository.Permission;
|
||||||
|
import sonia.scm.repository.PermissionType;
|
||||||
|
import sonia.scm.repository.Repository;
|
||||||
|
import sonia.scm.repository.RepositoryManager;
|
||||||
|
import sonia.scm.web.VndMediaType;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.URI;
|
||||||
|
import java.net.URISyntaxException;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.function.Consumer;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
|
import static de.otto.edison.hal.Link.link;
|
||||||
|
import static de.otto.edison.hal.Links.linkingTo;
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import static org.junit.Assert.fail;
|
||||||
|
import static org.junit.jupiter.api.DynamicTest.dynamicTest;
|
||||||
|
import static org.mockito.Matchers.any;
|
||||||
|
import static org.mockito.Mockito.doThrow;
|
||||||
|
import static org.mockito.Mockito.eq;
|
||||||
|
import static org.mockito.Mockito.mock;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
import static org.mockito.MockitoAnnotations.initMocks;
|
||||||
|
|
||||||
|
@Slf4j
|
||||||
|
@SubjectAware(
|
||||||
|
username = "trillian",
|
||||||
|
password = "secret",
|
||||||
|
configuration = "classpath:sonia/scm/repository/shiro.ini"
|
||||||
|
)
|
||||||
|
public class PermissionRootResourceTest {
|
||||||
|
private static final String REPOSITORY_NAMESPACE = "repo_namespace";
|
||||||
|
private static final String REPOSITORY_NAME = "repo";
|
||||||
|
private static final String PERMISSION_WRITE = "repository:permissionWrite:" + REPOSITORY_NAME;
|
||||||
|
private static final String PERMISSION_READ = "repository:permissionRead:" + REPOSITORY_NAME;
|
||||||
|
private static final String PERMISSION_OWNER = "repository:modify:" + REPOSITORY_NAME;
|
||||||
|
|
||||||
|
private static final String PERMISSION_NAME = "perm";
|
||||||
|
private static final String PATH_OF_ALL_PERMISSIONS = REPOSITORY_NAMESPACE + "/" + REPOSITORY_NAME + "/permissions/";
|
||||||
|
private static final String PATH_OF_ONE_PERMISSION = PATH_OF_ALL_PERMISSIONS + PERMISSION_NAME;
|
||||||
|
private static final String PERMISSION_TEST_PAYLOAD = "{ \"name\" : \"permission_name\", \"type\" : \"READ\" }";
|
||||||
|
private static final ArrayList<Permission> TEST_PERMISSIONS = Lists
|
||||||
|
.newArrayList(
|
||||||
|
new Permission("user_write", PermissionType.WRITE, false),
|
||||||
|
new Permission("user_read", PermissionType.READ, false),
|
||||||
|
new Permission("user_owner", PermissionType.OWNER, false),
|
||||||
|
new Permission("group_read", PermissionType.READ, true),
|
||||||
|
new Permission("group_write", PermissionType.WRITE, true),
|
||||||
|
new Permission("group_owner", PermissionType.OWNER, true)
|
||||||
|
);
|
||||||
|
private final ExpectedRequest requestGETAllPermissions = new ExpectedRequest()
|
||||||
|
.description("GET all permissions")
|
||||||
|
.method("GET")
|
||||||
|
.path(PATH_OF_ALL_PERMISSIONS);
|
||||||
|
private final ExpectedRequest requestPOSTPermission = new ExpectedRequest()
|
||||||
|
.description("create new permission")
|
||||||
|
.method("POST")
|
||||||
|
.content(PERMISSION_TEST_PAYLOAD)
|
||||||
|
.path(PATH_OF_ALL_PERMISSIONS);
|
||||||
|
private final ExpectedRequest requestGETPermission = new ExpectedRequest()
|
||||||
|
.description("GET permission")
|
||||||
|
.method("GET")
|
||||||
|
.path(PATH_OF_ONE_PERMISSION);
|
||||||
|
private final ExpectedRequest requestDELETEPermission = new ExpectedRequest()
|
||||||
|
.description("delete permission")
|
||||||
|
.method("DELETE")
|
||||||
|
.path(PATH_OF_ONE_PERMISSION);
|
||||||
|
private final ExpectedRequest requestPUTPermission = new ExpectedRequest()
|
||||||
|
.description("update permission")
|
||||||
|
.method("PUT")
|
||||||
|
.content(PERMISSION_TEST_PAYLOAD)
|
||||||
|
.path(PATH_OF_ONE_PERMISSION);
|
||||||
|
|
||||||
|
private final Dispatcher dispatcher = MockDispatcherFactory.createDispatcher();
|
||||||
|
|
||||||
|
@Rule
|
||||||
|
public ShiroRule shiro = new ShiroRule();
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private RepositoryManager repositoryManager;
|
||||||
|
|
||||||
|
private final URI baseUri = URI.create("/");
|
||||||
|
private final ResourceLinks resourceLinks = ResourceLinksMock.createMock(baseUri);
|
||||||
|
|
||||||
|
@InjectMocks
|
||||||
|
private PermissionToPermissionDtoMapperImpl permissionToPermissionDtoMapper;
|
||||||
|
|
||||||
|
@InjectMocks
|
||||||
|
private PermissionDtoToPermissionMapperImpl permissionDtoToPermissionMapper;
|
||||||
|
|
||||||
|
private PermissionCollectionToDtoMapper permissionCollectionToDtoMapper;
|
||||||
|
|
||||||
|
private PermissionRootResource permissionRootResource;
|
||||||
|
|
||||||
|
private final Subject subject = mock(Subject.class);
|
||||||
|
private final ThreadState subjectThreadState = new SubjectThreadState(subject);
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
@Before
|
||||||
|
public void prepareEnvironment() {
|
||||||
|
initMocks(this);
|
||||||
|
permissionCollectionToDtoMapper = new PermissionCollectionToDtoMapper(permissionToPermissionDtoMapper, resourceLinks);
|
||||||
|
permissionRootResource = new PermissionRootResource(permissionDtoToPermissionMapper, permissionToPermissionDtoMapper, permissionCollectionToDtoMapper, resourceLinks, repositoryManager);
|
||||||
|
RepositoryRootResource repositoryRootResource = new RepositoryRootResource(MockProvider
|
||||||
|
.of(new RepositoryResource(null, null, null, null, null, null, null, null, MockProvider.of(permissionRootResource))), null);
|
||||||
|
subjectThreadState.bind();
|
||||||
|
ThreadContext.bind(subject);
|
||||||
|
dispatcher.getRegistry().addSingletonResource(repositoryRootResource);
|
||||||
|
dispatcher.getProviderFactory().registerProvider(RepositoryNotFoundExceptionMapper.class);
|
||||||
|
dispatcher.getProviderFactory().registerProvider(PermissionNotFoundExceptionMapper.class);
|
||||||
|
dispatcher.getProviderFactory().registerProvider(PermissionAlreadyExistsExceptionMapper.class);
|
||||||
|
dispatcher.getProviderFactory().registerProvider(AuthorizationExceptionMapper.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
@After
|
||||||
|
public void unbind() {
|
||||||
|
ThreadContext.unbindSubject();
|
||||||
|
}
|
||||||
|
|
||||||
|
@TestFactory
|
||||||
|
@DisplayName("test endpoints on missing repository")
|
||||||
|
Stream<DynamicTest> missedRepositoryTestFactory() {
|
||||||
|
return createDynamicTestsToAssertResponses(
|
||||||
|
requestGETAllPermissions.expectedResponseStatus(404),
|
||||||
|
requestGETPermission.expectedResponseStatus(404),
|
||||||
|
requestPOSTPermission.expectedResponseStatus(404),
|
||||||
|
requestDELETEPermission.expectedResponseStatus(404),
|
||||||
|
requestPUTPermission.expectedResponseStatus(404));
|
||||||
|
}
|
||||||
|
|
||||||
|
@TestFactory
|
||||||
|
@DisplayName("test endpoints on missing permissions and user is Admin")
|
||||||
|
Stream<DynamicTest> missedPermissionTestFactory() {
|
||||||
|
Repository mockRepository = mock(Repository.class);
|
||||||
|
when(mockRepository.getId()).thenReturn(REPOSITORY_NAME);
|
||||||
|
when(mockRepository.getNamespace()).thenReturn(REPOSITORY_NAMESPACE);
|
||||||
|
when(mockRepository.getName()).thenReturn(REPOSITORY_NAME);
|
||||||
|
when(repositoryManager.get(any(NamespaceAndName.class))).thenReturn(mockRepository);
|
||||||
|
return createDynamicTestsToAssertResponses(
|
||||||
|
requestGETPermission.expectedResponseStatus(404),
|
||||||
|
requestPOSTPermission.expectedResponseStatus(201),
|
||||||
|
requestGETAllPermissions.expectedResponseStatus(200),
|
||||||
|
requestDELETEPermission.expectedResponseStatus(204),
|
||||||
|
requestPUTPermission.expectedResponseStatus(404));
|
||||||
|
}
|
||||||
|
|
||||||
|
@TestFactory
|
||||||
|
@DisplayName("test endpoints on missing permissions and user is not Admin")
|
||||||
|
Stream<DynamicTest> missedPermissionUserForbiddenTestFactory() {
|
||||||
|
Repository mockRepository = mock(Repository.class);
|
||||||
|
when(mockRepository.getId()).thenReturn(REPOSITORY_NAME);
|
||||||
|
when(mockRepository.getNamespace()).thenReturn(REPOSITORY_NAMESPACE);
|
||||||
|
when(mockRepository.getName()).thenReturn(REPOSITORY_NAME);
|
||||||
|
doThrow(AuthorizationException.class).when(repositoryManager).get(any(NamespaceAndName.class));
|
||||||
|
return createDynamicTestsToAssertResponses(
|
||||||
|
requestGETPermission.expectedResponseStatus(403),
|
||||||
|
requestPOSTPermission.expectedResponseStatus(403),
|
||||||
|
requestGETAllPermissions.expectedResponseStatus(403),
|
||||||
|
requestDELETEPermission.expectedResponseStatus(403),
|
||||||
|
requestPUTPermission.expectedResponseStatus(403));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void userWithPermissionWritePermissionShouldGetAllPermissionsWithCreateAndUpdateLinks() throws URISyntaxException {
|
||||||
|
createUserWithRepositoryAndPermissions(TEST_PERMISSIONS, PERMISSION_WRITE);
|
||||||
|
assertGettingExpectedPermissions(ImmutableList.copyOf(TEST_PERMISSIONS), PERMISSION_WRITE);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void userWithPermissionReadPermissionShouldGetAllPermissionsWithoutCreateAndUpdateLinks() throws URISyntaxException {
|
||||||
|
createUserWithRepositoryAndPermissions(TEST_PERMISSIONS, PERMISSION_READ);
|
||||||
|
assertGettingExpectedPermissions(ImmutableList.copyOf(TEST_PERMISSIONS), PERMISSION_READ);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldGetAllPermissions() throws URISyntaxException {
|
||||||
|
createUserWithRepositoryAndPermissions(TEST_PERMISSIONS, PERMISSION_READ);
|
||||||
|
assertGettingExpectedPermissions(ImmutableList.copyOf(TEST_PERMISSIONS), PERMISSION_READ);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldGetPermissionByName() throws URISyntaxException {
|
||||||
|
createUserWithRepositoryAndPermissions(TEST_PERMISSIONS, PERMISSION_READ);
|
||||||
|
Permission expectedPermission = TEST_PERMISSIONS.get(0);
|
||||||
|
assertExpectedRequest(requestGETPermission
|
||||||
|
.expectedResponseStatus(200)
|
||||||
|
.path(PATH_OF_ALL_PERMISSIONS + expectedPermission.getName())
|
||||||
|
.responseValidator((response) -> {
|
||||||
|
String body = response.getContentAsString();
|
||||||
|
ObjectMapper mapper = new ObjectMapper();
|
||||||
|
try {
|
||||||
|
PermissionDto actualPermissionDto = mapper.readValue(body, PermissionDto.class);
|
||||||
|
assertThat(actualPermissionDto)
|
||||||
|
.as("response payload match permission object model")
|
||||||
|
.isEqualToComparingFieldByFieldRecursively(getExpectedPermissionDto(expectedPermission, PERMISSION_READ))
|
||||||
|
;
|
||||||
|
} catch (IOException e) {
|
||||||
|
fail();
|
||||||
|
}
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldGetCreatedPermissions() throws URISyntaxException {
|
||||||
|
createUserWithRepositoryAndPermissions(TEST_PERMISSIONS, PERMISSION_WRITE);
|
||||||
|
Permission newPermission = new Permission("new_group_perm", PermissionType.WRITE, true);
|
||||||
|
ArrayList<Permission> permissions = Lists.newArrayList(TEST_PERMISSIONS);
|
||||||
|
permissions.add(newPermission);
|
||||||
|
ImmutableList<Permission> expectedPermissions = ImmutableList.copyOf(permissions);
|
||||||
|
assertExpectedRequest(requestPOSTPermission
|
||||||
|
.content("{\"name\" : \"" + newPermission.getName() + "\" , \"type\" : \"WRITE\" , \"groupPermission\" : true}")
|
||||||
|
.expectedResponseStatus(201)
|
||||||
|
.responseValidator(response -> assertThat(response.getContentAsString())
|
||||||
|
.as("POST response has no body")
|
||||||
|
.isBlank())
|
||||||
|
);
|
||||||
|
assertGettingExpectedPermissions(expectedPermissions, PERMISSION_WRITE);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldNotAddExistingPermission() throws URISyntaxException {
|
||||||
|
createUserWithRepositoryAndPermissions(TEST_PERMISSIONS, PERMISSION_WRITE);
|
||||||
|
Permission newPermission = TEST_PERMISSIONS.get(0);
|
||||||
|
assertExpectedRequest(requestPOSTPermission
|
||||||
|
.content("{\"name\" : \"" + newPermission.getName() + "\" , \"type\" : \"WRITE\" , \"groupPermission\" : true}")
|
||||||
|
.expectedResponseStatus(409)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldGetUpdatedPermissions() throws URISyntaxException {
|
||||||
|
createUserWithRepositoryAndPermissions(TEST_PERMISSIONS, PERMISSION_WRITE);
|
||||||
|
Permission modifiedPermission = TEST_PERMISSIONS.get(0);
|
||||||
|
// modify the type to owner
|
||||||
|
modifiedPermission.setType(PermissionType.OWNER);
|
||||||
|
ImmutableList<Permission> expectedPermissions = ImmutableList.copyOf(TEST_PERMISSIONS);
|
||||||
|
assertExpectedRequest(requestPUTPermission
|
||||||
|
.content("{\"name\" : \"" + modifiedPermission.getName() + "\" , \"type\" : \"OWNER\" , \"groupPermission\" : false}")
|
||||||
|
.path(PATH_OF_ALL_PERMISSIONS + modifiedPermission.getName())
|
||||||
|
.expectedResponseStatus(204)
|
||||||
|
.responseValidator(response -> assertThat(response.getContentAsString())
|
||||||
|
.as("PUT response has no body")
|
||||||
|
.isBlank())
|
||||||
|
);
|
||||||
|
assertGettingExpectedPermissions(expectedPermissions, PERMISSION_WRITE);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldDeletePermissions() throws URISyntaxException {
|
||||||
|
createUserWithRepositoryAndPermissions(TEST_PERMISSIONS, PERMISSION_OWNER);
|
||||||
|
Permission deletedPermission = TEST_PERMISSIONS.get(0);
|
||||||
|
ImmutableList<Permission> expectedPermissions = ImmutableList.copyOf(TEST_PERMISSIONS.subList(1, TEST_PERMISSIONS.size()));
|
||||||
|
assertExpectedRequest(requestDELETEPermission
|
||||||
|
.path(PATH_OF_ALL_PERMISSIONS + deletedPermission.getName())
|
||||||
|
.expectedResponseStatus(204)
|
||||||
|
.responseValidator(response -> assertThat(response.getContentAsString())
|
||||||
|
.as("DELETE response has no body")
|
||||||
|
.isBlank())
|
||||||
|
);
|
||||||
|
assertGettingExpectedPermissions(expectedPermissions, PERMISSION_READ);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void deletingNotExistingPermissionShouldProcess() throws URISyntaxException {
|
||||||
|
createUserWithRepositoryAndPermissions(TEST_PERMISSIONS, PERMISSION_OWNER);
|
||||||
|
Permission deletedPermission = TEST_PERMISSIONS.get(0);
|
||||||
|
ImmutableList<Permission> expectedPermissions = ImmutableList.copyOf(TEST_PERMISSIONS.subList(1, TEST_PERMISSIONS.size()));
|
||||||
|
assertExpectedRequest(requestDELETEPermission
|
||||||
|
.path(PATH_OF_ALL_PERMISSIONS + deletedPermission.getName())
|
||||||
|
.expectedResponseStatus(204)
|
||||||
|
.responseValidator(response -> assertThat(response.getContentAsString())
|
||||||
|
.as("DELETE response has no body")
|
||||||
|
.isBlank())
|
||||||
|
);
|
||||||
|
assertGettingExpectedPermissions(expectedPermissions, PERMISSION_READ);
|
||||||
|
assertExpectedRequest(requestDELETEPermission
|
||||||
|
.path(PATH_OF_ALL_PERMISSIONS + deletedPermission.getName())
|
||||||
|
.expectedResponseStatus(204)
|
||||||
|
.responseValidator(response -> assertThat(response.getContentAsString())
|
||||||
|
.as("DELETE response has no body")
|
||||||
|
.isBlank())
|
||||||
|
);
|
||||||
|
assertGettingExpectedPermissions(expectedPermissions, PERMISSION_READ);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void assertGettingExpectedPermissions(ImmutableList<Permission> expectedPermissions, String userPermission) throws URISyntaxException {
|
||||||
|
assertExpectedRequest(requestGETAllPermissions
|
||||||
|
.expectedResponseStatus(200)
|
||||||
|
.responseValidator((response) -> {
|
||||||
|
String body = response.getContentAsString();
|
||||||
|
ObjectMapper mapper = new ObjectMapper();
|
||||||
|
try {
|
||||||
|
HalRepresentation halRepresentation = mapper.readValue(body, HalRepresentation.class);
|
||||||
|
List<HalRepresentation> actualPermissionDtos = halRepresentation.getEmbedded().getItemsBy("permissions", HalRepresentation.class);
|
||||||
|
List<PermissionDto> permissionDtoStream = actualPermissionDtos.stream()
|
||||||
|
.map(hal -> {
|
||||||
|
PermissionDto result = new PermissionDto();
|
||||||
|
result.setName(hal.getAttribute("name").asText());
|
||||||
|
result.setType(hal.getAttribute("type").asText());
|
||||||
|
result.setGroupPermission(hal.getAttribute("groupPermission").asBoolean());
|
||||||
|
result.add(hal.getLinks());
|
||||||
|
return result;
|
||||||
|
}).collect(Collectors.toList());
|
||||||
|
assertThat(permissionDtoStream)
|
||||||
|
.as("response payload match permission object models")
|
||||||
|
.hasSize(expectedPermissions.size())
|
||||||
|
.usingRecursiveFieldByFieldElementComparator()
|
||||||
|
.containsExactlyInAnyOrder(getExpectedPermissionDtos(Lists.newArrayList(expectedPermissions), userPermission))
|
||||||
|
;
|
||||||
|
} catch (IOException e) {
|
||||||
|
fail();
|
||||||
|
}
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private PermissionDto[] getExpectedPermissionDtos(ArrayList<Permission> permissions, String userPermission) {
|
||||||
|
return permissions
|
||||||
|
.stream()
|
||||||
|
.map(p -> getExpectedPermissionDto(p, userPermission))
|
||||||
|
.toArray(PermissionDto[]::new);
|
||||||
|
}
|
||||||
|
|
||||||
|
private PermissionDto getExpectedPermissionDto(Permission permission, String userPermission) {
|
||||||
|
PermissionDto result = new PermissionDto();
|
||||||
|
result.setName(permission.getName());
|
||||||
|
result.setGroupPermission(permission.isGroupPermission());
|
||||||
|
result.setType(permission.getType().name());
|
||||||
|
String permissionHref = "/" + RepositoryRootResource.REPOSITORIES_PATH_V2 + PATH_OF_ALL_PERMISSIONS + permission.getName();
|
||||||
|
if (PERMISSION_READ.equals(userPermission)) {
|
||||||
|
result.add(linkingTo()
|
||||||
|
.self(permissionHref)
|
||||||
|
.build());
|
||||||
|
} else {
|
||||||
|
result.add(linkingTo()
|
||||||
|
.self(permissionHref)
|
||||||
|
.single(link("update", permissionHref))
|
||||||
|
.single(link("delete", permissionHref))
|
||||||
|
.build());
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
private Repository createUserWithRepository(String userPermission) {
|
||||||
|
Repository mockRepository = mock(Repository.class);
|
||||||
|
when(mockRepository.getId()).thenReturn(REPOSITORY_NAME);
|
||||||
|
when(mockRepository.getNamespace()).thenReturn(REPOSITORY_NAMESPACE);
|
||||||
|
when(mockRepository.getName()).thenReturn(REPOSITORY_NAME);
|
||||||
|
when(repositoryManager.get(any(NamespaceAndName.class))).thenReturn(mockRepository);
|
||||||
|
when(subject.isPermitted(userPermission != null ? eq(userPermission) : any(String.class))).thenReturn(true);
|
||||||
|
return mockRepository;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void createUserWithRepositoryAndPermissions(ArrayList<Permission> permissions, String userPermission) {
|
||||||
|
when(createUserWithRepository(userPermission).getPermissions()).thenReturn(permissions);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Stream<DynamicTest> createDynamicTestsToAssertResponses(ExpectedRequest... expectedRequests) {
|
||||||
|
return Stream.of(expectedRequests)
|
||||||
|
.map(entry -> dynamicTest("the endpoint " + entry.description + " should return the status code " + entry.expectedResponseStatus, () -> assertExpectedRequest(entry)));
|
||||||
|
}
|
||||||
|
|
||||||
|
private MockHttpResponse assertExpectedRequest(ExpectedRequest entry) throws URISyntaxException {
|
||||||
|
MockHttpResponse response = new MockHttpResponse();
|
||||||
|
HttpRequest request = null;
|
||||||
|
request = MockHttpRequest
|
||||||
|
.create(entry.method, "/" + RepositoryRootResource.REPOSITORIES_PATH_V2 + entry.path)
|
||||||
|
.content(entry.content)
|
||||||
|
.contentType(VndMediaType.PERMISSION);
|
||||||
|
dispatcher.invoke(request, response);
|
||||||
|
log.info("Test the Request :{}", entry);
|
||||||
|
assertThat(response.getStatus())
|
||||||
|
.as("assert status code")
|
||||||
|
.isEqualTo(entry.expectedResponseStatus);
|
||||||
|
if (entry.responseValidator != null) {
|
||||||
|
entry.responseValidator.accept(response);
|
||||||
|
}
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
|
||||||
|
@ToString
|
||||||
|
public class ExpectedRequest {
|
||||||
|
private String description;
|
||||||
|
private String method;
|
||||||
|
private String path;
|
||||||
|
private int expectedResponseStatus;
|
||||||
|
private byte[] content = new byte[]{};
|
||||||
|
private Consumer<MockHttpResponse> responseValidator;
|
||||||
|
|
||||||
|
public ExpectedRequest description(String description) {
|
||||||
|
this.description = description;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public ExpectedRequest method(String method) {
|
||||||
|
this.method = method;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public ExpectedRequest path(String path) {
|
||||||
|
this.path = path;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public ExpectedRequest content(String content) {
|
||||||
|
if (content != null) {
|
||||||
|
this.content = content.getBytes();
|
||||||
|
}
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public ExpectedRequest expectedResponseStatus(int expectedResponseStatus) {
|
||||||
|
this.expectedResponseStatus = expectedResponseStatus;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public ExpectedRequest responseValidator(Consumer<MockHttpResponse> responseValidator) {
|
||||||
|
this.responseValidator = responseValidator;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -11,10 +11,13 @@ import org.junit.Before;
|
|||||||
import org.junit.Rule;
|
import org.junit.Rule;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
import org.mockito.Answers;
|
import org.mockito.Answers;
|
||||||
|
import org.mockito.ArgumentCaptor;
|
||||||
import org.mockito.InjectMocks;
|
import org.mockito.InjectMocks;
|
||||||
import org.mockito.Mock;
|
import org.mockito.Mock;
|
||||||
import sonia.scm.PageResult;
|
import sonia.scm.PageResult;
|
||||||
import sonia.scm.repository.NamespaceAndName;
|
import sonia.scm.repository.NamespaceAndName;
|
||||||
|
import sonia.scm.repository.Permission;
|
||||||
|
import sonia.scm.repository.PermissionType;
|
||||||
import sonia.scm.repository.Repository;
|
import sonia.scm.repository.Repository;
|
||||||
import sonia.scm.repository.RepositoryException;
|
import sonia.scm.repository.RepositoryException;
|
||||||
import sonia.scm.repository.RepositoryIsNotArchivedException;
|
import sonia.scm.repository.RepositoryIsNotArchivedException;
|
||||||
@@ -35,10 +38,13 @@ import static javax.servlet.http.HttpServletResponse.SC_NO_CONTENT;
|
|||||||
import static javax.servlet.http.HttpServletResponse.SC_OK;
|
import static javax.servlet.http.HttpServletResponse.SC_OK;
|
||||||
import static javax.servlet.http.HttpServletResponse.SC_PRECONDITION_FAILED;
|
import static javax.servlet.http.HttpServletResponse.SC_PRECONDITION_FAILED;
|
||||||
import static org.junit.Assert.assertEquals;
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertFalse;
|
||||||
import static org.junit.Assert.assertTrue;
|
import static org.junit.Assert.assertTrue;
|
||||||
|
import static org.mockito.ArgumentCaptor.forClass;
|
||||||
import static org.mockito.Matchers.any;
|
import static org.mockito.Matchers.any;
|
||||||
import static org.mockito.Matchers.anyObject;
|
import static org.mockito.Matchers.anyObject;
|
||||||
import static org.mockito.Matchers.eq;
|
import static org.mockito.Matchers.eq;
|
||||||
|
import static org.mockito.Mockito.doNothing;
|
||||||
import static org.mockito.Mockito.doThrow;
|
import static org.mockito.Mockito.doThrow;
|
||||||
import static org.mockito.Mockito.never;
|
import static org.mockito.Mockito.never;
|
||||||
import static org.mockito.Mockito.verify;
|
import static org.mockito.Mockito.verify;
|
||||||
@@ -240,6 +246,28 @@ public class RepositoryRootResourceTest {
|
|||||||
verify(repositoryManager).create(any(Repository.class));
|
verify(repositoryManager).create(any(Repository.class));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldNotOverwriteExistingPermissionsOnUpdate() throws Exception {
|
||||||
|
Repository existingRepository = mockRepository("space", "repo");
|
||||||
|
existingRepository.setPermissions(singletonList(new Permission("user", PermissionType.READ)));
|
||||||
|
|
||||||
|
URL url = Resources.getResource("sonia/scm/api/v2/repository-test-update.json");
|
||||||
|
byte[] repository = Resources.toByteArray(url);
|
||||||
|
|
||||||
|
ArgumentCaptor<Repository> modifiedRepositoryCaptor = forClass(Repository.class);
|
||||||
|
doNothing().when(repositoryManager).modify(modifiedRepositoryCaptor.capture());
|
||||||
|
|
||||||
|
MockHttpRequest request = MockHttpRequest
|
||||||
|
.put("/" + RepositoryRootResource.REPOSITORIES_PATH_V2 + "space/repo")
|
||||||
|
.contentType(VndMediaType.REPOSITORY)
|
||||||
|
.content(repository);
|
||||||
|
MockHttpResponse response = new MockHttpResponse();
|
||||||
|
|
||||||
|
dispatcher.invoke(request, response);
|
||||||
|
|
||||||
|
assertFalse(modifiedRepositoryCaptor.getValue().getPermissions().isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
private PageResult<Repository> createSingletonPageResult(Repository repository) {
|
private PageResult<Repository> createSingletonPageResult(Repository repository) {
|
||||||
return new PageResult<>(singletonList(repository), 0);
|
return new PageResult<>(singletonList(repository), 0);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ public class ResourceLinksMock {
|
|||||||
when(resourceLinks.branchCollection()).thenReturn(new ResourceLinks.BranchCollectionLinks(uriInfo));
|
when(resourceLinks.branchCollection()).thenReturn(new ResourceLinks.BranchCollectionLinks(uriInfo));
|
||||||
when(resourceLinks.changeset()).thenReturn(new ResourceLinks.ChangesetLinks(uriInfo));
|
when(resourceLinks.changeset()).thenReturn(new ResourceLinks.ChangesetLinks(uriInfo));
|
||||||
when(resourceLinks.source()).thenReturn(new ResourceLinks.SourceLinks(uriInfo));
|
when(resourceLinks.source()).thenReturn(new ResourceLinks.SourceLinks(uriInfo));
|
||||||
when(resourceLinks.permissionCollection()).thenReturn(new ResourceLinks.PermissionCollectionLinks(uriInfo));
|
when(resourceLinks.permission()).thenReturn(new ResourceLinks.PermissionLinks(uriInfo));
|
||||||
when(resourceLinks.config()).thenReturn(new ResourceLinks.ConfigLinks(uriInfo));
|
when(resourceLinks.config()).thenReturn(new ResourceLinks.ConfigLinks(uriInfo));
|
||||||
when(resourceLinks.branch()).thenReturn(new ResourceLinks.BranchLinks(uriInfo));
|
when(resourceLinks.branch()).thenReturn(new ResourceLinks.BranchLinks(uriInfo));
|
||||||
when(resourceLinks.repositoryType()).thenReturn(new ResourceLinks.RepositoryTypeLinks(uriInfo));
|
when(resourceLinks.repositoryType()).thenReturn(new ResourceLinks.RepositoryTypeLinks(uriInfo));
|
||||||
|
|||||||
@@ -120,15 +120,15 @@ public final class IntegrationTestUtil
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static Collection<String> createRepositoryTypeParameters() {
|
public static Collection<String[]> createRepositoryTypeParameters() {
|
||||||
Collection<String> params = new ArrayList<>();
|
Collection<String[]> params = new ArrayList<>();
|
||||||
|
|
||||||
params.add("git");
|
params.add(new String[]{"git"});
|
||||||
params.add("svn" );
|
params.add(new String[]{"svn"});
|
||||||
|
|
||||||
if (IOUtil.search("hg") != null)
|
if (IOUtil.search("hg") != null)
|
||||||
{
|
{
|
||||||
params.add("hg");
|
params.add(new String[]{"hg"});
|
||||||
}
|
}
|
||||||
|
|
||||||
return params;
|
return params;
|
||||||
|
|||||||
@@ -81,7 +81,7 @@ public class RepositoryArchiveITCase
|
|||||||
//~--- methods --------------------------------------------------------------
|
//~--- methods --------------------------------------------------------------
|
||||||
|
|
||||||
@Parameterized.Parameters(name = "{0}")
|
@Parameterized.Parameters(name = "{0}")
|
||||||
public static Collection<String> createParameters() {
|
public static Collection<String[]> createParameters() {
|
||||||
return IntegrationTestUtil.createRepositoryTypeParameters();
|
return IntegrationTestUtil.createRepositoryTypeParameters();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -208,7 +208,7 @@ public class RepositoryHookITCase extends AbstractAdminITCaseBase
|
|||||||
* @return repository types test parameter
|
* @return repository types test parameter
|
||||||
*/
|
*/
|
||||||
@Parameters(name = "{0}")
|
@Parameters(name = "{0}")
|
||||||
public static Collection<String> createParameters()
|
public static Collection<String[]> createParameters()
|
||||||
{
|
{
|
||||||
return IntegrationTestUtil.createRepositoryTypeParameters();
|
return IntegrationTestUtil.createRepositoryTypeParameters();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -40,15 +40,12 @@ import org.apache.shiro.authz.SimpleAuthorizationInfo;
|
|||||||
import org.apache.shiro.subject.SimplePrincipalCollection;
|
import org.apache.shiro.subject.SimplePrincipalCollection;
|
||||||
import org.apache.shiro.subject.Subject;
|
import org.apache.shiro.subject.Subject;
|
||||||
import org.hamcrest.Matchers;
|
import org.hamcrest.Matchers;
|
||||||
import org.junit.Test;
|
|
||||||
import org.junit.Before;
|
import org.junit.Before;
|
||||||
|
import org.junit.Rule;
|
||||||
|
import org.junit.Test;
|
||||||
import org.junit.runner.RunWith;
|
import org.junit.runner.RunWith;
|
||||||
import org.mockito.Mock;
|
import org.mockito.Mock;
|
||||||
import org.mockito.Mockito;
|
import org.mockito.Mockito;
|
||||||
import static org.mockito.Mockito.*;
|
|
||||||
import static org.hamcrest.Matchers.*;
|
|
||||||
import static org.junit.Assert.*;
|
|
||||||
import org.junit.Rule;
|
|
||||||
import org.mockito.junit.MockitoJUnitRunner;
|
import org.mockito.junit.MockitoJUnitRunner;
|
||||||
import sonia.scm.cache.Cache;
|
import sonia.scm.cache.Cache;
|
||||||
import sonia.scm.cache.CacheManager;
|
import sonia.scm.cache.CacheManager;
|
||||||
@@ -60,6 +57,16 @@ import sonia.scm.repository.RepositoryTestData;
|
|||||||
import sonia.scm.user.User;
|
import sonia.scm.user.User;
|
||||||
import sonia.scm.user.UserTestData;
|
import sonia.scm.user.UserTestData;
|
||||||
|
|
||||||
|
import static org.hamcrest.Matchers.containsInAnyOrder;
|
||||||
|
import static org.hamcrest.Matchers.hasSize;
|
||||||
|
import static org.hamcrest.Matchers.nullValue;
|
||||||
|
import static org.junit.Assert.assertSame;
|
||||||
|
import static org.junit.Assert.assertThat;
|
||||||
|
import static org.mockito.Mockito.any;
|
||||||
|
import static org.mockito.Mockito.anyObject;
|
||||||
|
import static org.mockito.Mockito.verify;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Unit tests for {@link AuthorizationCollector}.
|
* Unit tests for {@link AuthorizationCollector}.
|
||||||
*
|
*
|
||||||
@@ -200,7 +207,7 @@ public class DefaultAuthorizationCollectorTest {
|
|||||||
AuthorizationInfo authInfo = collector.collect();
|
AuthorizationInfo authInfo = collector.collect();
|
||||||
assertThat(authInfo.getRoles(), Matchers.containsInAnyOrder(Role.USER));
|
assertThat(authInfo.getRoles(), Matchers.containsInAnyOrder(Role.USER));
|
||||||
assertThat(authInfo.getObjectPermissions(), nullValue());
|
assertThat(authInfo.getObjectPermissions(), nullValue());
|
||||||
assertThat(authInfo.getStringPermissions(), containsInAnyOrder("repository:read:one", "repository:read,write:two"));
|
assertThat(authInfo.getStringPermissions(), containsInAnyOrder("repository:read,pull:one", "repository:read,pull,push:two"));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
Reference in New Issue
Block a user