Reduce SecurityFilter to user injection and enable SecurityInterceptor

Remove all the unnecessary stuff and all endpoints that would be no
longer secure.
This commit is contained in:
René Pfeuffer
2018-11-09 16:06:31 +01:00
parent 42bf785a42
commit 96c2114e53
21 changed files with 86 additions and 2005 deletions

View File

@@ -128,7 +128,6 @@ import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import static com.google.inject.matcher.Matchers.annotatedWith;
import static com.google.inject.matcher.Matchers.any;
import static com.google.inject.matcher.Matchers.not;
import static com.google.inject.matcher.Matchers.subclassesOf;
import static sonia.scm.api.v2.resources.ScmPathInfo.REST_API_PATH;

View File

@@ -0,0 +1,13 @@
package sonia.scm.api.rest;
import org.apache.shiro.authc.AuthenticationException;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.Provider;
@Provider
public class AuthenticationExceptionMapper extends StatusExceptionMapper<AuthenticationException> {
public AuthenticationExceptionMapper() {
super(AuthenticationException.class, Response.Status.UNAUTHORIZED);
}
}

View File

@@ -26,7 +26,11 @@ public class ContextualExceptionMapper<E extends ExceptionWithContext> implement
@Override
public Response toResponse(E exception) {
logger.debug("map {} to status code {}", type.getSimpleName(), status.getStatusCode(), exception);
if (logger.isTraceEnabled()) {
logger.trace("map {} to status code {}", type.getSimpleName(), status.getStatusCode(), exception);
} else {
logger.debug("map {} to status code {} with message '{}'", type.getSimpleName(), status.getStatusCode(), exception.getMessage());
}
return Response.status(status)
.entity(mapper.map(exception))
.type(VndMediaType.ERROR_TYPE)

View File

@@ -0,0 +1,13 @@
package sonia.scm.api.rest;
import javax.ws.rs.NotAuthorizedException;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.Provider;
@Provider
public class NotAuthorizedExceptionMapper extends StatusExceptionMapper<NotAuthorizedException> {
public NotAuthorizedExceptionMapper()
{
super(NotAuthorizedException.class, Response.Status.UNAUTHORIZED);
}
}

View File

@@ -1,148 +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.google.inject.Singleton;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import sonia.scm.config.ScmConfiguration;
import sonia.scm.security.Role;
import sonia.scm.security.ScmSecurityException;
import sonia.scm.util.ScmConfigurationUtil;
//~--- JDK imports ------------------------------------------------------------
import javax.ws.rs.Consumes;
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.ws.rs.core.UriInfo;
/**
*
* @author Sebastian Sdorra
*/
@Singleton
@Path("config")
public class ConfigurationResource
{
/**
* Constructs ...
*
*
* @param configuration
* @param securityContextProvider
*/
@Inject
public ConfigurationResource(ScmConfiguration configuration)
{
this.configuration = configuration;
}
//~--- get methods ----------------------------------------------------------
/**
* Method description
*
*
* @return
*/
@GET
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response getConfiguration()
{
Response response = null;
if (SecurityUtils.getSubject().hasRole(Role.ADMIN))
{
response = Response.ok(configuration).build();
}
else
{
response = Response.status(Response.Status.FORBIDDEN).build();
}
return response;
}
//~--- set methods ----------------------------------------------------------
/**
* Method description
*
*
* @param uriInfo
* @param newConfig
*
* @return
*/
@POST
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response setConfig(@Context UriInfo uriInfo,
ScmConfiguration newConfig)
{
// TODO replace by checkRole
Subject subject = SecurityUtils.getSubject();
if (!subject.hasRole(Role.ADMIN))
{
throw new ScmSecurityException("admin privileges required");
}
configuration.load(newConfig);
synchronized (ScmConfiguration.class)
{
ScmConfigurationUtil.getInstance().store(configuration);
}
return Response.created(uriInfo.getRequestUri()).build();
}
//~--- fields ---------------------------------------------------------------
/** Field description */
public ScmConfiguration configuration;
}

View File

@@ -1,248 +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.google.inject.Singleton;
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 sonia.scm.group.Group;
import sonia.scm.group.GroupManager;
import sonia.scm.security.Role;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
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.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.GenericEntity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import java.util.Collection;
//~--- JDK imports ------------------------------------------------------------
/**
* RESTful Web Service Resource to manage groups and their members.
*
* @author Sebastian Sdorra
*/
@Path("groups")
@Singleton
public class GroupResource extends AbstractManagerResource<Group> {
/** Field description */
public static final String PATH_PART = "groups";
//~--- constructors ---------------------------------------------------------
@Inject
public GroupResource(GroupManager groupManager)
{
super(groupManager, Group.class);
}
//~--- methods --------------------------------------------------------------
/**
* Creates a new group. <strong>Note:</strong> This method requires admin privileges.
*
* @param uriInfo current uri informations
* @param group the group to be created
*
* @return
*/
@POST
@StatusCodes({
@ResponseCode(code = 201, condition = "create success", additionalHeaders = {
@ResponseHeader(name = "Location", description = "uri to the created group")
}),
@ResponseCode(code = 403, condition = "forbidden, the current user has no admin privileges"),
@ResponseCode(code = 500, condition = "internal server error")
})
@TypeHint(TypeHint.NO_CONTENT.class)
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Override
public Response create(@Context UriInfo uriInfo, Group group)
{
return super.create(uriInfo, group);
}
/**
* Deletes a group. <strong>Note:</strong> This method requires admin privileges.
*
* @param name the name of the group to delete.
*
* @return
*/
@DELETE
@Path("{id}")
@StatusCodes({
@ResponseCode(code = 204, condition = "delete success"),
@ResponseCode(code = 403, condition = "forbidden, the current user has no admin privileges"),
@ResponseCode(code = 500, condition = "internal server error")
})
@TypeHint(TypeHint.NO_CONTENT.class)
@Override
public Response delete(@PathParam("id") String name)
{
return super.delete(name);
}
/**
* Modifies the given group. <strong>Note:</strong> This method requires admin privileges.
*
* @param name name of the group to be modified
* @param group group object to modify
*
* @return
*/
@PUT
@Path("{id}")
@StatusCodes({
@ResponseCode(code = 204, condition = "update success"),
@ResponseCode(code = 403, condition = "forbidden, the current user has no admin privileges"),
@ResponseCode(code = 500, condition = "internal server error")
})
@TypeHint(TypeHint.NO_CONTENT.class)
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Override
public Response update(@PathParam("id") String name, Group group)
{
return super.update(name, group);
}
//~--- get methods ----------------------------------------------------------
/**
* Fetches a group by its name or id. <strong>Note:</strong> This method requires admin privileges.
*
* @param request the current request
* @param id the id/name of the group
*
* @return the {@link Group} with the specified id
*/
@GET
@Path("{id}")
@TypeHint(Group.class)
@StatusCodes({
@ResponseCode(code = 200, condition = "success"),
@ResponseCode(code = 403, condition = "forbidden, the current user has no admin privileges"),
@ResponseCode(code = 404, condition = "not found, no group with the specified id/name available"),
@ResponseCode(code = 500, condition = "internal server error")
})
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Override
public Response get(@Context Request request, @PathParam("id") String id)
{
Response response = null;
if (SecurityUtils.getSubject().hasRole(Role.ADMIN))
{
response = super.get(request, id);
}
else
{
response = Response.status(Response.Status.FORBIDDEN).build();
}
return response;
}
/**
* Returns all groups. <strong>Note:</strong> This method requires admin privileges.
*
* @param request the current request
* @param start the start value for paging
* @param limit the limit value for paging
* @param sortby sort parameter
* @param desc sort direction desc or aesc
*
* @return
*/
@GET
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@TypeHint(Group[].class)
@StatusCodes({
@ResponseCode(code = 200, condition = "success"),
@ResponseCode(code = 403, condition = "forbidden, the current user has no admin privileges"),
@ResponseCode(code = 500, condition = "internal server error")
})
@Override
public Response getAll(@Context Request request, @DefaultValue("0")
@QueryParam("start") int start, @DefaultValue("-1")
@QueryParam("limit") int limit, @QueryParam("sortby") String sortby,
@DefaultValue("false")
@QueryParam("desc") boolean desc)
{
return super.getAll(request, start, limit, sortby, desc);
}
//~--- methods --------------------------------------------------------------
@Override
protected GenericEntity<Collection<Group>> createGenericEntity(
Collection<Group> items)
{
return new GenericEntity<Collection<Group>>(items) {}
;
}
//~--- get methods ----------------------------------------------------------
@Override
protected String getId(Group group)
{
return group.getName();
}
@Override
protected String getPathPart()
{
return PATH_PART;
}
}

View File

@@ -1,362 +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.inject.Inject;
import com.google.inject.Singleton;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sonia.scm.api.rest.RestActionResult;
import sonia.scm.api.rest.RestActionUploadResult;
import sonia.scm.plugin.OverviewPluginPredicate;
import sonia.scm.plugin.PluginConditionFailedException;
import sonia.scm.plugin.PluginInformation;
import sonia.scm.plugin.PluginInformationComparator;
import sonia.scm.plugin.PluginManager;
//~--- JDK imports ------------------------------------------------------------
import com.webcohesion.enunciate.metadata.rs.ResponseCode;
import com.webcohesion.enunciate.metadata.rs.StatusCodes;
import com.webcohesion.enunciate.metadata.rs.TypeHint;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import javax.ws.rs.Consumes;
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.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
/**
* RESTful Web Service Endpoint to manage plugins.
*
* @author Sebastian Sdorra
*/
@Singleton
@Path("plugins")
public class PluginResource
{
/**
* the logger for PluginResource
*/
private static final Logger logger =
LoggerFactory.getLogger(PluginResource.class);
//~--- constructors ---------------------------------------------------------
/**
* Constructs ...
*
*
* @param pluginManager
*/
@Inject
public PluginResource(PluginManager pluginManager)
{
this.pluginManager = pluginManager;
}
//~--- methods --------------------------------------------------------------
/**
* Installs a plugin from a package.
*
* @param uploadedInputStream
*
* @return
*
* @throws IOException
*/
@POST
@Path("install-package")
@StatusCodes({
@ResponseCode(code = 200, condition = "success"),
@ResponseCode(code = 412, condition = "precondition failed"),
@ResponseCode(code = 500, condition = "internal server error")
})
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response install(
/*@FormParam("package")*/ InputStream uploadedInputStream)
throws IOException
{
Response response = null;
try
{
pluginManager.installPackage(uploadedInputStream);
response = Response.ok(new RestActionUploadResult(true)).build();
}
catch (PluginConditionFailedException ex)
{
logger.warn(
"could not install plugin package, because the condition failed", ex);
response = Response.status(Status.PRECONDITION_FAILED).entity(
new RestActionResult(false)).build();
}
catch (Exception ex)
{
logger.warn("plugin installation failed", ex);
response =
Response.serverError().entity(new RestActionResult(false)).build();
}
return response;
}
/**
* Installs a plugin.
*
* @param id id of the plugin to be installed
*
* @return
*/
@POST
@StatusCodes({
@ResponseCode(code = 200, condition = "success"),
@ResponseCode(code = 500, condition = "internal server error")
})
@TypeHint(TypeHint.NO_CONTENT.class)
@Path("install/{id}")
public Response install(@PathParam("id") String id)
{
pluginManager.install(id);
// TODO should return 204 no content
return Response.ok().build();
}
/**
* Installs a plugin from a package. This method is a workaround for ExtJS
* file upload, which requires text/html as content-type.
*
* @param uploadedInputStream
* @return
*
* @throws IOException
*/
@POST
@Path("install-package.html")
@StatusCodes({
@ResponseCode(code = 200, condition = "success"),
@ResponseCode(code = 412, condition = "precondition failed"),
@ResponseCode(code = 500, condition = "internal server error")
})
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.TEXT_HTML)
public Response installFromUI(
/*@FormParam("package")*/ InputStream uploadedInputStream)
throws IOException
{
return install(uploadedInputStream);
}
/**
* Uninstalls a plugin.
*
* @param id id of the plugin to be uninstalled
*
* @return
*/
@POST
@StatusCodes({
@ResponseCode(code = 200, condition = "success"),
@ResponseCode(code = 500, condition = "internal server error")
})
@Path("uninstall/{id}")
public Response uninstall(@PathParam("id") String id)
{
pluginManager.uninstall(id);
// TODO should return 204 content
// consider to do a uninstall with a delete
return Response.ok().build();
}
/**
* Updates a plugin.
*
* @param id id of the plugin to be updated
*
* @return
*/
@POST
@StatusCodes({
@ResponseCode(code = 200, condition = "success"),
@ResponseCode(code = 500, condition = "internal server error")
})
@Path("update/{id}")
public Response update(@PathParam("id") String id)
{
pluginManager.update(id);
// TODO should return 204 content
// consider to do an update with a put
return Response.ok().build();
}
//~--- get methods ----------------------------------------------------------
/**
* Returns all plugins.
*
* @return all plugins
*/
@GET
@StatusCodes({
@ResponseCode(code = 200, condition = "success"),
@ResponseCode(code = 500, condition = "internal server error")
})
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Collection<PluginInformation> getAll()
{
return pluginManager.getAll();
}
/**
* Returns all available plugins.
*
* @return all available plugins
*/
@GET
@Path("available")
@StatusCodes({
@ResponseCode(code = 200, condition = "success"),
@ResponseCode(code = 500, condition = "internal server error")
})
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Collection<PluginInformation> getAvailable()
{
return pluginManager.getAvailable();
}
/**
* Returns all plugins which are available for update.
*
* @return all plugins which are available for update
*/
@GET
@Path("updates")
@StatusCodes({
@ResponseCode(code = 200, condition = "success"),
@ResponseCode(code = 500, condition = "internal server error")
})
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Collection<PluginInformation> getAvailableUpdates()
{
return pluginManager.getAvailableUpdates();
}
/**
* Returns all installed plugins.
*
* @return all installed plugins
*/
@GET
@Path("installed")
@StatusCodes({
@ResponseCode(code = 200, condition = "success"),
@ResponseCode(code = 500, condition = "internal server error")
})
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public Collection<PluginInformation> getInstalled()
{
return pluginManager.getInstalled();
}
/**
* Returns all plugins for the overview.
*
* @return all plugins for the overview
*/
@GET
@Path("overview")
@StatusCodes({
@ResponseCode(code = 200, condition = "success"),
@ResponseCode(code = 500, condition = "internal server error")
})
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Collection<PluginInformation> getOverview()
{
//J-
List<PluginInformation> plugins = Lists.newArrayList(
pluginManager.get(OverviewPluginPredicate.INSTANCE)
);
//J+
Collections.sort(plugins, PluginInformationComparator.INSTANCE);
Iterator<PluginInformation> it = plugins.iterator();
String last = null;
while (it.hasNext())
{
PluginInformation pi = it.next();
String id = pi.getId(false);
if ((last != null) && id.equals(last))
{
it.remove();
}
last = id;
}
return plugins;
}
//~--- fields ---------------------------------------------------------------
/** plugin manager */
private final PluginManager pluginManager;
}

View File

@@ -1,319 +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.google.inject.Singleton;
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.apache.shiro.authc.credential.PasswordService;
import sonia.scm.security.Role;
import sonia.scm.user.User;
import sonia.scm.user.UserManager;
import sonia.scm.util.AssertUtil;
import sonia.scm.util.Util;
import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
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.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.GenericEntity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import java.util.Collection;
//~--- JDK imports ------------------------------------------------------------
/**
* RESTful Web Service Resource to manage users.
*
* @author Sebastian Sdorra
*/
@Singleton
@Path("users")
public class UserResource extends AbstractManagerResource<User>
{
/** Field description */
public static final String DUMMY_PASSWORT = "__dummypassword__";
/** Field description */
public static final String PATH_PART = "users";
//~--- constructors ---------------------------------------------------------
/**
* Constructs ...
*
*
* @param userManager
* @param passwordService
*/
@Inject
public UserResource(UserManager userManager, PasswordService passwordService)
{
super(userManager, User.class);
this.passwordService = passwordService;
}
//~--- methods --------------------------------------------------------------
/**
* Creates a new user. <strong>Note:</strong> This method requires admin privileges.
*
* @param uriInfo current uri informations
* @param user the user to be created
*
* @return
*/
@POST
@StatusCodes({
@ResponseCode(code = 201, condition = "create success", additionalHeaders = {
@ResponseHeader(name = "Location", description = "uri to the created group")
}),
@ResponseCode(code = 403, condition = "forbidden, the current user has no admin privileges"),
@ResponseCode(code = 500, condition = "internal server error")
})
@TypeHint(TypeHint.NO_CONTENT.class)
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Override
public Response create(@Context UriInfo uriInfo, User user)
{
return super.create(uriInfo, user);
}
/**
* Deletes a user. <strong>Note:</strong> This method requires admin privileges.
*
* @param name the name of the user to delete.
*
* @return
*/
@DELETE
@Path("{id}")
@StatusCodes({
@ResponseCode(code = 204, condition = "delete success"),
@ResponseCode(code = 403, condition = "forbidden, the current user has no admin privileges"),
@ResponseCode(code = 500, condition = "internal server error")
})
@TypeHint(TypeHint.NO_CONTENT.class)
@Override
public Response delete(@PathParam("id") String name)
{
return super.delete(name);
}
/**
* Modifies the given user. <strong>Note:</strong> This method requires admin privileges.
*
* @param name name of the user to be modified
* @param user user object to modify
*
* @return
*/
@PUT
@Path("{id}")
@StatusCodes({
@ResponseCode(code = 204, condition = "update success"),
@ResponseCode(code = 403, condition = "forbidden, the current user has no admin privileges"),
@ResponseCode(code = 500, condition = "internal server error")
})
@TypeHint(TypeHint.NO_CONTENT.class)
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Override
public Response update(@PathParam("id") String name, User user)
{
return super.update(name, user);
}
//~--- get methods ----------------------------------------------------------
/**
* Returns a user. <strong>Note:</strong> This method requires admin privileges.
*
* @param request the current request
* @param id the id/name of the user
*
* @return the {@link User} with the specified id
*/
@GET
@Path("{id}")
@TypeHint(User.class)
@StatusCodes({
@ResponseCode(code = 200, condition = "success"),
@ResponseCode(code = 403, condition = "forbidden, the current user has no admin privileges"),
@ResponseCode(code = 404, condition = "not found, no group with the specified id/name available"),
@ResponseCode(code = 500, condition = "internal server error")
})
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Override
public Response get(@Context Request request, @PathParam("id") String id)
{
Response response = null;
if (SecurityUtils.getSubject().hasRole(Role.ADMIN))
{
response = super.get(request, id);
}
else
{
response = Response.status(Response.Status.FORBIDDEN).build();
}
return response;
}
/**
* Returns all users. <strong>Note:</strong> This method requires admin privileges.
*
* @param request the current request
* @param start the start value for paging
* @param limit the limit value for paging
* @param sortby sort parameter
* @param desc sort direction desc or aesc
*
* @return
*/
@GET
@TypeHint(User[].class)
@StatusCodes({
@ResponseCode(code = 200, condition = "success"),
@ResponseCode(code = 403, condition = "forbidden, the current user has no admin privileges"),
@ResponseCode(code = 500, condition = "internal server error")
})
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Override
public Response getAll(@Context Request request, @DefaultValue("0")
@QueryParam("start") int start, @DefaultValue("-1")
@QueryParam("limit") int limit, @QueryParam("sortby") String sortby,
@DefaultValue("false")
@QueryParam("desc") boolean desc)
{
return super.getAll(request, start, limit, sortby, desc);
}
//~--- methods --------------------------------------------------------------
@Override
protected GenericEntity<Collection<User>> createGenericEntity(
Collection<User> items)
{
return new GenericEntity<Collection<User>>(items) {}
;
}
@Override
protected void preCreate(User user)
{
encryptPassword(user);
}
@Override
protected void preUpdate(User user)
{
if (DUMMY_PASSWORT.equals(user.getPassword()))
{
User o = manager.get(user.getName());
AssertUtil.assertIsNotNull(o);
user.setPassword(o.getPassword());
}
else
{
encryptPassword(user);
}
}
@Override
protected Collection<User> prepareForReturn(Collection<User> users)
{
if (Util.isNotEmpty(users))
{
for (User u : users)
{
u.setPassword(DUMMY_PASSWORT);
}
}
return users;
}
@Override
protected User prepareForReturn(User user)
{
user.setPassword(DUMMY_PASSWORT);
return user;
}
@Override
protected String getId(User user)
{
return user.getName();
}
@Override
protected String getPathPart()
{
return PATH_PART;
}
private void encryptPassword(User user)
{
String password = user.getPassword();
if (Util.isNotEmpty(password))
{
user.setPassword(passwordService.encryptPassword(password));
}
}
//~--- fields ---------------------------------------------------------------
/** Field description */
private PasswordService passwordService;
}

View File

@@ -18,6 +18,7 @@ import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@Path(AuthenticationResource.PATH)
@AllowAnonymousAccess
public class AuthenticationResource {
private static final Logger LOG = LoggerFactory.getLogger(AuthenticationResource.class);

View File

@@ -1,6 +1,7 @@
package sonia.scm.api.v2.resources;
import com.webcohesion.enunciate.metadata.rs.TypeHint;
import sonia.scm.security.AllowAnonymousAccess;
import sonia.scm.web.VndMediaType;
import javax.inject.Inject;
@@ -9,6 +10,7 @@ import javax.ws.rs.Path;
import javax.ws.rs.Produces;
@Path(IndexResource.INDEX_PATH_V2)
@AllowAnonymousAccess
public class IndexResource {
public static final String INDEX_PATH_V2 = "v2/";

View File

@@ -5,6 +5,7 @@ import com.webcohesion.enunciate.metadata.rs.StatusCodes;
import com.webcohesion.enunciate.metadata.rs.TypeHint;
import sonia.scm.plugin.PluginLoader;
import sonia.scm.plugin.PluginWrapper;
import sonia.scm.security.AllowAnonymousAccess;
import sonia.scm.web.VndMediaType;
import javax.inject.Inject;
@@ -17,6 +18,7 @@ import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
@AllowAnonymousAccess
public class UIPluginResource {
private final PluginLoader pluginLoader;

View File

@@ -1,90 +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.filter;
//~--- non-JDK imports --------------------------------------------------------
import com.google.inject.Inject;
import org.apache.shiro.subject.Subject;
import sonia.scm.Priority;
import sonia.scm.config.ScmConfiguration;
import sonia.scm.security.Role;
/**
* Security filter which allow only administrators to access the underlying
* resources.
*
* @author Sebastian Sdorra
*/
// TODO before releasing v2, delete this filter (we use Permission objects now)
@WebElement(
value = Filters.PATTERN_CONFIG,
morePatterns = {
Filters.PATTERN_USERS,
Filters.PATTERN_GROUPS,
Filters.PATTERN_PLUGINS
}
)
@Priority(Filters.PRIORITY_AUTHORIZATION + 1)
public class AdminSecurityFilter extends SecurityFilter
{
/**
* Constructs a new instance.
*
* @param configuration scm-manager main configuration
*/
@Inject
public AdminSecurityFilter(ScmConfiguration configuration)
{
super(configuration);
}
//~--- get methods ----------------------------------------------------------
/**
* Returns {@code true} if the subject has the admin role.
*
* @param subject subject
*
* @return {@code true} if the subject has the admin role
*/
@Override
protected boolean hasPermission(Subject subject)
{
return subject.hasRole(Role.ADMIN);
}
}

View File

@@ -62,8 +62,7 @@ import static sonia.scm.api.v2.resources.ScmPathInfo.REST_API_PATH;
*/
@Priority(Filters.PRIORITY_AUTHORIZATION)
// TODO find a better way for unprotected resources
@WebElement(value = REST_API_PATH + "" +
"/(?!v2/ui).*", regex = true)
@WebElement(value = REST_API_PATH + "/(?!v2/ui).*", regex = true)
public class SecurityFilter extends HttpFilter
{
@@ -84,31 +83,16 @@ public class SecurityFilter extends HttpFilter
HttpServletResponse response, FilterChain chain)
throws IOException, ServletException
{
if (!SecurityRequests.isAuthenticationRequest(request) && !SecurityRequests.isIndexRequest(request))
Subject subject = SecurityUtils.getSubject();
if (hasPermission(subject))
{
Subject subject = SecurityUtils.getSubject();
if (hasPermission(subject))
{
// add primary principal as request attribute
// see https://goo.gl/JRjNmf
String username = getUsername(subject);
request.setAttribute(ATTRIBUTE_REMOTE_USER, username);
// add primary principal as request attribute
// see https://goo.gl/JRjNmf
String username = getUsername(subject);
request.setAttribute(ATTRIBUTE_REMOTE_USER, username);
// wrap servlet request to provide authentication informations
chain.doFilter(new SecurityHttpServletRequestWrapper(request, username), response);
}
else if (subject.isAuthenticated() || subject.isRemembered())
{
response.sendError(HttpServletResponse.SC_FORBIDDEN);
}
else if (configuration.isAnonymousAccessEnabled())
{
response.sendError(HttpServletResponse.SC_FORBIDDEN);
}
else
{
response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
}
// wrap servlet request to provide authentication information
chain.doFilter(new SecurityHttpServletRequestWrapper(request, username), response);
}
else
{
@@ -116,7 +100,7 @@ public class SecurityFilter extends HttpFilter
}
}
protected boolean hasPermission(Subject subject)
private boolean hasPermission(Subject subject)
{
return ((configuration != null)
&& configuration.isAnonymousAccessEnabled()) || subject.isAuthenticated()
@@ -139,5 +123,4 @@ public class SecurityFilter extends HttpFilter
return username;
}
}

View File

@@ -0,0 +1,11 @@
package sonia.scm.security;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface AllowAnonymousAccess {
}

View File

@@ -2,11 +2,28 @@ package sonia.scm.security;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.subject.Subject;
public class SecurityInterceptor implements MethodInterceptor {
@Override
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
return methodInvocation.proceed();
if (hasPermission() || anonymousAccessIsAllowed(methodInvocation)) {
return methodInvocation.proceed();
} else {
throw new AuthenticationException();
}
}
private boolean anonymousAccessIsAllowed(MethodInvocation methodInvocation) {
return methodInvocation.getMethod().isAnnotationPresent(AllowAnonymousAccess.class)
|| methodInvocation.getMethod().getDeclaringClass().isAnnotationPresent(AllowAnonymousAccess.class);
}
private boolean hasPermission() {
Subject subject = SecurityUtils.getSubject();
return subject.isAuthenticated() || subject.isRemembered();
}
}