removes admin role

This commit is contained in:
Sebastian Sdorra
2019-03-21 10:46:11 +01:00
parent 3e9f59ef47
commit 7c6bfdaaac
15 changed files with 40 additions and 1736 deletions

View File

@@ -1,463 +0,0 @@
/**
* 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.api.rest.resources;
//~--- non-JDK imports --------------------------------------------------------
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.webcohesion.enunciate.metadata.rs.ResponseCode;
import com.webcohesion.enunciate.metadata.rs.StatusCodes;
import com.webcohesion.enunciate.metadata.rs.TypeHint;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sonia.scm.ScmState;
import sonia.scm.ScmStateFactory;
import sonia.scm.api.rest.RestActionResult;
import sonia.scm.config.ScmConfiguration;
import sonia.scm.security.Tokens;
import sonia.scm.util.HttpUtil;
//~--- JDK imports ------------------------------------------------------------
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import sonia.scm.security.AccessToken;
import sonia.scm.security.AccessTokenBuilder;
import sonia.scm.security.AccessTokenBuilderFactory;
import sonia.scm.security.AccessTokenCookieIssuer;
import sonia.scm.security.Scope;
/**
* Authentication related RESTful Web Service endpoint.
*
* @author Sebastian Sdorra
*/
@Singleton
@Path("auth")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public class AuthenticationResource
{
/** the logger for AuthenticationResource */
private static final Logger logger =
LoggerFactory.getLogger(AuthenticationResource.class);
//~--- constant enums -------------------------------------------------------
/**
* Enum description
*
*/
private static enum WUIAuthenticationFailure { LOCKED, TEMPORARY_LOCKED,
WRONG_CREDENTIALS; }
//~--- constructors ---------------------------------------------------------
/**
* Constructs ...
*
*
* @param configuration
* @param stateFactory
* @param tokenBuilderFactory
* @param cookieIssuer
*/
@Inject
public AuthenticationResource(ScmConfiguration configuration,
ScmStateFactory stateFactory, AccessTokenBuilderFactory tokenBuilderFactory, AccessTokenCookieIssuer cookieIssuer)
{
this.configuration = configuration;
this.stateFactory = stateFactory;
this.tokenBuilderFactory = tokenBuilderFactory;
this.cookieIssuer = cookieIssuer;
}
//~--- methods --------------------------------------------------------------
/**
* Authenticate a user and return the state of the application.
*
* @param request current http request
* @param response current http response
* @param grantType grant type, currently only password is supported
* @param username the username for the authentication
* @param password the password for the authentication
* @param cookie create authentication token
* @param scope scope of created token
*
* @return
*/
@POST
@Path("access_token")
@TypeHint(ScmState.class)
@StatusCodes({
@ResponseCode(code = 200, condition = "success"),
@ResponseCode(code = 400, condition = "bad request, required parameter is missing"),
@ResponseCode(code = 401, condition = "unauthorized, the specified username or password is wrong"),
@ResponseCode(code = 500, condition = "internal server error")
})
public Response authenticate(
@Context HttpServletRequest request,
@Context HttpServletResponse response,
@FormParam("grant_type") String grantType,
@FormParam("username") String username,
@FormParam("password") String password,
@FormParam("cookie") boolean cookie,
@FormParam("scope") List<String> scope)
{
Preconditions.checkArgument(!Strings.isNullOrEmpty(grantType), "grant_type parameter is required");
Preconditions.checkArgument(!Strings.isNullOrEmpty(username), "username parameter is required");
Preconditions.checkArgument(!Strings.isNullOrEmpty(password), "password parameter is required");
Response res;
Subject subject = SecurityUtils.getSubject();
try
{
subject.login(Tokens.createAuthenticationToken(request, username, password));
AccessTokenBuilder tokenBuilder = tokenBuilderFactory.create();
if ( scope != null ) {
tokenBuilder.scope(Scope.valueOf(scope));
}
AccessToken token = tokenBuilder.build();
ScmState state;
if (cookie) {
cookieIssuer.authenticate(request, response, token);
state = stateFactory.createState(subject);
} else {
state = stateFactory.createState(subject, token.compact());
}
res = Response.ok(state).build();
}
catch (DisabledAccountException ex)
{
if (logger.isTraceEnabled())
{
logger.trace(
"authentication failed, account user ".concat(username).concat(
" is locked"), ex);
}
else
{
logger.warn("authentication failed, account {} is locked", username);
}
res = handleFailedAuthentication(request, ex, Response.Status.FORBIDDEN,
WUIAuthenticationFailure.LOCKED);
}
catch (ExcessiveAttemptsException ex)
{
if (logger.isTraceEnabled())
{
logger.trace(
"authentication failed, account user ".concat(username).concat(
" is temporary locked"), ex);
}
else
{
logger.warn("authentication failed, account {} is temporary locked", username);
}
res = handleFailedAuthentication(request, ex, Response.Status.FORBIDDEN,
WUIAuthenticationFailure.TEMPORARY_LOCKED);
}
catch (AuthenticationException ex)
{
if (logger.isTraceEnabled())
{
logger.trace("authentication failed for user ".concat(username), ex);
}
else
{
logger.warn("authentication failed for user {}", username);
}
res = handleFailedAuthentication(request, ex, Response.Status.UNAUTHORIZED,
WUIAuthenticationFailure.WRONG_CREDENTIALS);
}
return res;
}
/**
* Logout the current user. Returns the current state of the application, if public access is enabled.
*
* @param request the current http request
* @param response the current http response
*
* @return
*/
@GET
@Path("logout")
@TypeHint(ScmState.class)
@StatusCodes({
@ResponseCode(code = 200, condition = "success"),
@ResponseCode(code = 500, condition = "internal server error")
})
public Response logout(@Context HttpServletRequest request, @Context HttpServletResponse response)
{
Subject subject = SecurityUtils.getSubject();
subject.logout();
// remove authentication cookie
cookieIssuer.invalidate(request, response);
Response resp;
if (configuration.isAnonymousAccessEnabled())
{
resp = Response.ok(stateFactory.createAnonymousState()).build();
}
else
{
resp = Response.ok().build();
}
return resp;
}
//~--- get methods ----------------------------------------------------------
/**
* This method is an alias of the {@link #getState(HttpServletRequest)} method.
* The only difference between the methods, is that this one could not be used with basic authentication.
*
* @param request the current http request
*
* @return
*/
@GET
@Path("state")
@TypeHint(ScmState.class)
@StatusCodes({
@ResponseCode(code = 200, condition = "success"),
@ResponseCode(code = 401, condition = "unauthorized, user is not authenticated and public access is disabled"),
@ResponseCode(code = 500, condition = "internal server error")
})
public Response getCurrentState(@Context HttpServletRequest request)
{
return getState(request);
}
/**
* Returns the current state of the application.
*
* @param request the current http request
*
* @return
*/
@GET
@TypeHint(ScmState.class)
@StatusCodes({
@ResponseCode(code = 200, condition = "success"),
@ResponseCode(code = 401, condition = "unauthorized, user is not authenticated and public access is disabled"),
@ResponseCode(code = 500, condition = "internal server error")
})
public Response getState(@Context HttpServletRequest request)
{
Response response;
Subject subject = SecurityUtils.getSubject();
if (subject.isAuthenticated() || subject.isRemembered())
{
if (logger.isDebugEnabled())
{
String auth = subject.isRemembered()
? "remembered"
: "authenticated";
logger.debug("return state for {} user {}", auth,
subject.getPrincipal());
}
ScmState state = stateFactory.createState(subject);
response = Response.ok(state).build();
}
else if (configuration.isAnonymousAccessEnabled())
{
response = Response.ok(stateFactory.createAnonymousState()).build();
}
else
{
response = Response.status(Response.Status.UNAUTHORIZED).build();
}
return response;
}
//~--- methods --------------------------------------------------------------
/**
* Method description
*
*
* @param request
* @param ex
* @param status
* @param failure
*
* @return
*/
private Response handleFailedAuthentication(HttpServletRequest request,
AuthenticationException ex, Response.Status status,
WUIAuthenticationFailure failure)
{
Response response;
if (HttpUtil.isWUIRequest(request))
{
response = Response.ok(new WUIAuthenticationFailedResult(failure,
ex.getMessage())).build();
}
else
{
response = Response.status(status).build();
}
return response;
}
//~--- inner classes --------------------------------------------------------
/**
* Class description
*
*
* @version Enter version here..., 13/09/28
* @author Enter your name here...
*/
@XmlRootElement(name = "result")
@XmlAccessorType(XmlAccessType.FIELD)
private static final class WUIAuthenticationFailedResult
extends RestActionResult
{
/**
* Constructs ...
*
*
* @param failure
* @param mesage
*/
public WUIAuthenticationFailedResult(WUIAuthenticationFailure failure,
String mesage)
{
super(false);
this.failure = failure;
this.mesage = mesage;
}
//~--- get methods --------------------------------------------------------
/**
* Method description
*
*
* @return
*/
public WUIAuthenticationFailure getFailure()
{
return failure;
}
/**
* Method description
*
*
* @return
*/
public String getMesage()
{
return mesage;
}
//~--- fields -------------------------------------------------------------
/** Field description */
private final WUIAuthenticationFailure failure;
/** Field description */
private final String mesage;
}
//~--- fields ---------------------------------------------------------------
/** Field description */
private final ScmConfiguration configuration;
/** Field description */
private final ScmStateFactory stateFactory;
/** Field description */
private final AccessTokenBuilderFactory tokenBuilderFactory;
/** Field description */
private final AccessTokenCookieIssuer cookieIssuer;
}

View File

@@ -1,87 +0,0 @@
/**
* 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.api.rest.resources;
//~--- non-JDK imports --------------------------------------------------------
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.webcohesion.enunciate.metadata.rs.ResponseCode;
import com.webcohesion.enunciate.metadata.rs.StatusCodes;
import org.apache.shiro.SecurityUtils;
import sonia.scm.security.CipherUtil;
import sonia.scm.security.Role;
//~--- JDK imports ------------------------------------------------------------
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
/**
* Rest resource to encrypt values.
*
* @author Sebastian Sdorra
* @since 1.41
*/
@Path("security/cipher")
public class CipherResource
{
/**
* Encrypts the request body and returns an encrypted string. This method can
* only executed with administration privileges.
*
* @param value value to encrypt
*
* @return unique key
*/
@POST
@Path("encrypt")
@StatusCodes({
@ResponseCode(code = 200, condition = "success"),
@ResponseCode(code = 500, condition = "internal server error")
})
@Produces(MediaType.TEXT_PLAIN)
public String encrypt(String value)
{
SecurityUtils.getSubject().checkRole(Role.ADMIN);
Preconditions.checkArgument(!Strings.isNullOrEmpty(value),
"value is required");
return CipherUtil.getInstance().encode(value);
}
}

View File

@@ -1,98 +0,0 @@
/**
* 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.api.rest.resources;
//~--- non-JDK imports --------------------------------------------------------
import com.google.inject.Inject;
import com.webcohesion.enunciate.metadata.rs.ResponseCode;
import com.webcohesion.enunciate.metadata.rs.StatusCodes;
import org.apache.shiro.SecurityUtils;
import sonia.scm.security.KeyGenerator;
import sonia.scm.security.Role;
//~--- JDK imports ------------------------------------------------------------
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
/**
* Rest resource to generate unique keys.
*
* @author Sebastian Sdorra
* @since 1.41
*/
@Path("security/key")
public class KeyResource
{
/**
* Constructs a new KeyResource.
*
*
* @param keyGenerator key generator
*/
@Inject
public KeyResource(KeyGenerator keyGenerator)
{
this.keyGenerator = keyGenerator;
}
//~--- methods --------------------------------------------------------------
/**
* Generates a unique key. <strong>Note:</strong> This method can only executed with administration privileges.
*
* @return unique key
*/
@GET
@StatusCodes({
@ResponseCode(code = 200, condition = "success"),
@ResponseCode(code = 500, condition = "internal server error")
})
@Produces(MediaType.TEXT_PLAIN)
public String generateKey()
{
SecurityUtils.getSubject().checkRole(Role.ADMIN);
return keyGenerator.createKey();
}
//~--- fields ---------------------------------------------------------------
/** key generator */
private final KeyGenerator keyGenerator;
}

View File

@@ -42,24 +42,43 @@ import com.webcohesion.enunciate.metadata.rs.ResponseCode;
import com.webcohesion.enunciate.metadata.rs.ResponseHeader;
import com.webcohesion.enunciate.metadata.rs.StatusCodes;
import com.webcohesion.enunciate.metadata.rs.TypeHint;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sonia.scm.NotFoundException;
import sonia.scm.FeatureNotSupportedException;
import sonia.scm.NotFoundException;
import sonia.scm.Type;
import sonia.scm.api.rest.RestActionUploadResult;
import sonia.scm.api.v2.resources.RepositoryResource;
import sonia.scm.repository.*;
import sonia.scm.repository.AdvancedImportHandler;
import sonia.scm.repository.ImportHandler;
import sonia.scm.repository.ImportResult;
import sonia.scm.repository.InternalRepositoryException;
import sonia.scm.repository.Repository;
import sonia.scm.repository.RepositoryHandler;
import sonia.scm.repository.RepositoryManager;
import sonia.scm.repository.RepositoryPermissions;
import sonia.scm.repository.RepositoryType;
import sonia.scm.repository.api.Command;
import sonia.scm.repository.api.RepositoryService;
import sonia.scm.repository.api.RepositoryServiceFactory;
import sonia.scm.repository.api.UnbundleCommandBuilder;
import sonia.scm.security.Role;
import sonia.scm.util.IOUtil;
import javax.ws.rs.*;
import javax.ws.rs.core.*;
import javax.ws.rs.Consumes;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.GenericEntity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
@@ -233,7 +252,7 @@ public class RepositoryImportResource
public Response importFromUrl(@Context UriInfo uriInfo,
@PathParam("type") String type, UrlImportRequest request)
{
SecurityUtils.getSubject().checkRole(Role.ADMIN);
RepositoryPermissions.create().check();
checkNotNull(request, "request is required");
checkArgument(!Strings.isNullOrEmpty(request.getName()),
"request does not contain name of the repository");
@@ -288,7 +307,7 @@ public class RepositoryImportResource
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response importRepositories(@PathParam("type") String type)
{
SecurityUtils.getSubject().checkRole(Role.ADMIN);
RepositoryPermissions.create().check();
List<Repository> repositories = new ArrayList<Repository>();
@@ -320,7 +339,7 @@ public class RepositoryImportResource
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response importRepositories()
{
SecurityUtils.getSubject().checkRole(Role.ADMIN);
RepositoryPermissions.create().check();
logger.info("start directory import for all supported repository types");
@@ -363,7 +382,7 @@ public class RepositoryImportResource
public Response importRepositoriesFromDirectory(
@PathParam("type") String type)
{
SecurityUtils.getSubject().checkRole(Role.ADMIN);
RepositoryPermissions.create().check();
Response response;
@@ -438,7 +457,7 @@ public class RepositoryImportResource
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response getImportableTypes()
{
SecurityUtils.getSubject().checkRole(Role.ADMIN);
RepositoryPermissions.create().check();
List<Type> types = findImportableTypes();
@@ -537,7 +556,7 @@ public class RepositoryImportResource
private Repository doImportFromBundle(String type, String name,
InputStream inputStream, boolean compressed)
{
SecurityUtils.getSubject().checkRole(Role.ADMIN);
RepositoryPermissions.create().check();
checkArgument(!Strings.isNullOrEmpty(name),
"request does not contain name of the repository");

View File

@@ -1,463 +0,0 @@
/**
* 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.api.rest.resources;
//~--- non-JDK imports --------------------------------------------------------
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.inject.Inject;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import sonia.scm.SCMContextProvider;
import sonia.scm.ServletContainerDetector;
import sonia.scm.Type;
import sonia.scm.config.ScmConfiguration;
import sonia.scm.plugin.PluginManager;
import sonia.scm.repository.RepositoryHandler;
import sonia.scm.repository.RepositoryManager;
import sonia.scm.security.Role;
import sonia.scm.security.ScmSecurityException;
import sonia.scm.util.SystemUtil;
//~--- JDK imports ------------------------------------------------------------
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import sonia.scm.store.ConfigurationStoreFactory;
import sonia.scm.template.Viewable;
/**
*
* @author Sebastian Sdorra
*/
@Path("support")
public class SupportResource
{
/** Field description */
public static final String TEMPLATE = "/templates/support.mustache";
//~--- constructors ---------------------------------------------------------
/**
* Constructs ...
*
*
*
* @param securityContext
* @param context
* @param templateHandler
* @param configuration
* @param pluginManager
* @param storeFactory
* @param repositoryManager
* @param request
*/
@Inject
public SupportResource(SCMContextProvider context,
ScmConfiguration configuration, PluginManager pluginManager,
ConfigurationStoreFactory storeFactory, RepositoryManager repositoryManager,
HttpServletRequest request)
{
this.context = context;
this.configuration = configuration;
this.pluginManager = pluginManager;
this.storeFactoryClass = storeFactory.getClass();
this.repositoryManager = repositoryManager;
this.request = request;
}
//~--- get methods ----------------------------------------------------------
/**
* Method description
*
*
* @return
*
* @throws IOException
*/
@GET
@Produces(MediaType.TEXT_HTML)
public Viewable getSupport() throws IOException
{
Subject subject = SecurityUtils.getSubject();
if (!subject.hasRole(Role.ADMIN))
{
throw new ScmSecurityException("admin privileges required");
}
Map<String, Object> env = Maps.newHashMap();
env.put("version", new VersionInformation(context, storeFactoryClass));
env.put("configuration", configuration);
env.put("pluginManager", pluginManager);
env.put("runtime", new RuntimeInformation());
env.put("system", new SystemInformation(request));
env.put("repositoryHandlers", getRepositoryHandlers());
return new Viewable(TEMPLATE, env);
}
/**
* Method description
*
*
* @return
*/
private List<RepositoryHandler> getRepositoryHandlers()
{
List<RepositoryHandler> handlers = Lists.newArrayList();
for (Type type : repositoryManager.getConfiguredTypes())
{
handlers.add(repositoryManager.getHandler(type.getName()));
}
return handlers;
}
//~--- inner classes --------------------------------------------------------
/**
* Class description
*
*
* @version Enter version here..., 12/04/30
* @author Enter your name here...
*/
public static class RuntimeInformation
{
/**
* Constructs ...
*
*/
public RuntimeInformation()
{
Runtime runtime = Runtime.getRuntime();
totalMemory = runtime.totalMemory();
freeMemory = runtime.freeMemory();
maxMemory = runtime.maxMemory();
availableProcessors = runtime.availableProcessors();
}
//~--- get methods --------------------------------------------------------
/**
* Method description
*
*
* @return
*/
public int getAvailableProcessors()
{
return availableProcessors;
}
/**
* Method description
*
*
* @return
*/
public long getFreeMemory()
{
return freeMemory;
}
/**
* Method description
*
*
* @return
*/
public long getMaxMemory()
{
return maxMemory;
}
/**
* Method description
*
*
* @return
*/
public long getTotalMemory()
{
return totalMemory;
}
//~--- fields -------------------------------------------------------------
/** Field description */
private int availableProcessors;
/** Field description */
private long freeMemory;
/** Field description */
private long maxMemory;
/** Field description */
private long totalMemory;
}
/**
* Class description
*
*
* @version Enter version here..., 12/04/30
* @author Enter your name here...
*/
public static class SystemInformation
{
/**
* Constructs ...
*
*
* @param request
*/
public SystemInformation(HttpServletRequest request)
{
os = SystemUtil.getOS();
arch = SystemUtil.getArch();
container = ServletContainerDetector.detect(request).name();
java = System.getProperty("java.vendor").concat("/").concat(
System.getProperty("java.version"));
locale = Locale.getDefault().toString();
timeZone = TimeZone.getDefault().getID();
}
//~--- get methods --------------------------------------------------------
/**
* Method description
*
*
* @return
*/
public String getArch()
{
return arch;
}
/**
* Method description
*
*
* @return
*/
public String getContainer()
{
return container;
}
/**
* Method description
*
*
* @return
*/
public String getJava()
{
return java;
}
/**
* Method description
*
*
* @return
*/
public String getLocale()
{
return locale;
}
/**
* Method description
*
*
* @return
*/
public String getOs()
{
return os;
}
/**
* Method description
*
*
* @return
*/
public String getTimeZone()
{
return timeZone;
}
//~--- fields -------------------------------------------------------------
/** Field description */
private String arch;
/** Field description */
private String container;
/** Field description */
private String java;
/** Field description */
private String locale;
/** Field description */
private String os;
/** Field description */
private String timeZone;
}
/**
* Class description
*
*
* @version Enter version here..., 12/04/30
* @author Enter your name here...
*/
public static class VersionInformation
{
/**
* Constructs ...
*
*
* @param context
* @param storeFactoryClass
*/
public VersionInformation(SCMContextProvider context,
Class<?> storeFactoryClass)
{
version = context.getVersion();
stage = context.getStage().name();
storeFactory = storeFactoryClass.getName();
}
//~--- get methods --------------------------------------------------------
/**
* Method description
*
*
* @return
*/
public String getStage()
{
return stage;
}
/**
* Method description
*
*
* @return
*/
public String getStoreFactory()
{
return storeFactory;
}
/**
* Method description
*
*
* @return
*/
public String getVersion()
{
return version;
}
//~--- fields -------------------------------------------------------------
/** Field description */
private String stage;
/** Field description */
private String storeFactory;
/** Field description */
private String version;
}
//~--- fields ---------------------------------------------------------------
/** Field description */
private ScmConfiguration configuration;
/** Field description */
private SCMContextProvider context;
/** Field description */
private PluginManager pluginManager;
/** Field description */
private RepositoryManager repositoryManager;
/** Field description */
private HttpServletRequest request;
/** Field description */
private Class<?> storeFactoryClass;
}

View File

@@ -36,6 +36,7 @@ import com.google.common.collect.Multimap;
import com.google.inject.Singleton;
import org.apache.shiro.SecurityUtils;
import sonia.scm.repository.NamespaceAndName;
import sonia.scm.repository.RepositoryPermissions;
import sonia.scm.security.Role;
import java.util.Collection;
@@ -63,7 +64,8 @@ public final class DebugService
* Returns the last received hook data for the given repository.
*/
public DebugHookData getLast(NamespaceAndName namespaceAndName){
SecurityUtils.getSubject().checkRole(Role.ADMIN);
// debug permission does not exists, so only accounts with "*" permission can use these resource
SecurityUtils.getSubject().checkPermission("debug");
DebugHookData hookData = null;
Collection<DebugHookData> receivedHookData = receivedHooks.get(namespaceAndName);
if (receivedHookData != null && ! receivedHookData.isEmpty()){
@@ -76,7 +78,8 @@ public final class DebugService
* Returns all received hook data for the given repository.
*/
public Collection<DebugHookData> getAll(NamespaceAndName namespaceAndName){
SecurityUtils.getSubject().checkRole(Role.ADMIN);
// debug permission does not exists, so only accounts with "*" permission can use these resource
SecurityUtils.getSubject().checkPermission("debug");
return receivedHooks.get(namespaceAndName);
}
}

View File

@@ -27,7 +27,7 @@ public class AdministrationContextRealm extends AuthorizingRealm {
AdministrationContextMarker marker = principals.oneByType(AdministrationContextMarker.class);
if (marker == AdministrationContextMarker.MARKER) {
LOG.info("assign admin permissions to admin context user {}", principals.getPrimaryPrincipal());
SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo(Sets.newHashSet(Role.USER, Role.ADMIN));
SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo(Sets.newHashSet(Role.USER));
authorizationInfo.setStringPermissions(Sets.newHashSet("*"));
return authorizationInfo;
}

View File

@@ -124,19 +124,7 @@ public class DefaultAdministrationContext implements AdministrationContext
if (ThreadContext.getSecurityManager() != null)
{
Subject subject = SecurityUtils.getSubject();
if (subject.hasRole(Role.ADMIN))
{
logger.debug(
"user is already an admin, we need no system account session, execute action {}",
action.getClass().getName());
action.run();
}
else
{
doRunAsInWebSessionContext(action);
}
doRunAsInWebSessionContext(action);
}
else
{