@Test( expected = ForbiddenException.class ) public void pingWithAuthzFailed() throws Exception { try { String res = getPingService().pingWithAuthz(); fail( "not in exception" ); } catch ( ForbiddenException e ) { assertEquals( 403, e.getResponse().getStatus() ); throw e; } }
@Test( expected = ForbiddenException.class ) public void deleteArtifactKarmaFailed() throws Exception { try { Artifact artifact = new Artifact(); artifact.setGroupId( "commons-logging" ); artifact.setArtifactId( "commons-logging" ); artifact.setVersion( "1.0.1" ); artifact.setPackaging( "jar" ); artifact.setContext( SOURCE_REPO_ID ); RepositoriesService repositoriesService = getRepositoriesService( null ); repositoriesService.deleteArtifact( artifact ); } catch ( ForbiddenException e ) { assertEquals( 403, e.getResponse().getStatus() ); throw e; } }
@Test public void testCreateException() { assertExceptionType(Response.Status.INTERNAL_SERVER_ERROR, InternalServerErrorException.class); assertExceptionType(Response.Status.NOT_FOUND, NotFoundException.class); assertExceptionType(Response.Status.FORBIDDEN, ForbiddenException.class); assertExceptionType(Response.Status.BAD_REQUEST, BadRequestException.class); assertExceptionType(Response.Status.METHOD_NOT_ALLOWED, NotAllowedException.class); assertExceptionType(Response.Status.UNAUTHORIZED, NotAuthorizedException.class); assertExceptionType(Response.Status.NOT_ACCEPTABLE, NotAcceptableException.class); assertExceptionType(Response.Status.UNSUPPORTED_MEDIA_TYPE, NotSupportedException.class); assertExceptionType(Response.Status.SERVICE_UNAVAILABLE, ServiceUnavailableException.class); assertExceptionType(Response.Status.TEMPORARY_REDIRECT, RedirectionException.class); assertExceptionType(Response.Status.LENGTH_REQUIRED, ClientErrorException.class); assertExceptionType(Response.Status.BAD_GATEWAY, ServerErrorException.class); assertExceptionType(Response.Status.NO_CONTENT, WebApplicationException.class); }
private HttpResponse authenticatedUser(HttpRequest request) { String userIdString = request.getProperty("userOverride"); if (userIdString == null) userIdString = userFrom(request) .map(UserId::id) .orElseThrow(() -> new ForbiddenException("You must be authenticated or specify userOverride")); UserId userId = new UserId(userIdString); List<Tenant> tenants = controller.tenants().asList(userId); Slime slime = new Slime(); Cursor response = slime.setObject(); response.setString("user", userId.id()); Cursor tenantsArray = response.setArray("tenants"); for (Tenant tenant : tenants) tenantInTenantsListToSlime(tenant, request.getUri(), tenantsArray.addObject()); response.setBool("tenantExists", tenants.stream().map(Tenant::getId).anyMatch(id -> id.isTenantFor(userId))); return new SlimeJsonResponse(slime); }
private HttpResponse createApplication(String tenantName, String applicationName, HttpRequest request) { authorizer.throwIfUnauthorized(new TenantId(tenantName), request); Application application; try { application = controller.applications().createApplication(ApplicationId.from(tenantName, applicationName, "default"), authorizer.getNToken(request)); } catch (ZmsException e) { // TODO: Push conversion down if (e.getCode() == com.yahoo.jdisc.Response.Status.FORBIDDEN) throw new ForbiddenException("Not authorized to create application", e); else throw e; } Slime slime = new Slime(); toSlime(application, slime.setObject(), request); return new SlimeJsonResponse(slime); }
@Override public void filter(ContainerRequestContext requestContext) throws IOException { Instance<Object> instance = CDI.current(); User user = instance.select(User.class).get(); List<AccountRole> roles = user.getAccountRoles(); if (Arrays.stream(permissions.roles()).anyMatch(roles::contains)) { return; } Permission permission = instance.select(permissions.value()).get(); if (permission.test(requestContext)) { return; } throw new ForbiddenException(); }
/** * When forbidden exception has been thrown */ @Test public void testReadEventsScenario5() { resetAll(); // test data final ReadEventsRequest request = getHelper().getReadEventsRequest(); final CronofyResponse<ReadEventsResponse> expectedResponse = new CronofyResponse<>( ErrorTypeModel.FORBIDDEN ); // expectations expect(client.target(BASE_PATH)).andThrow(new ForbiddenException()); replayAll(); final CronofyResponse<ReadEventsResponse> result = cronofyClient.readEvents(request); getHelper().assertResultResponse(expectedResponse, result); verifyAll(); }
/** * When forbidden exception has been thrown */ @Test public void testFreeBusyScenario4() { resetAll(); // test data final FreeBusyRequest request = getHelper().getFreeBusyRequest(); final CronofyResponse<FreeBusyResponse> expectedResponse = new CronofyResponse<>( ErrorTypeModel.FORBIDDEN ); // expectations expect(client.target(BASE_PATH)).andThrow(new ForbiddenException()); replayAll(); final CronofyResponse<FreeBusyResponse> result = cronofyClient.freeBusy(request); getHelper().assertResultResponse(expectedResponse, result); verifyAll(); }
@Test public void test() { printHeader("Sending entity request for text:\n\n" + Configuration.TEXT_DE); try { // Request the resource with plain text final EntityResult result = resource.getAll(Configuration.TEXT_DE); printResult(result); } catch (ForbiddenException e) { // Handle forbidden response which is supposed to be caused by an invalid API key System.err.println("Exception while calling Midas webservice: " + e.getMessage()); System.err.println("Maybe the API key \"" + Configuration.API_KEY + "\" is invalid."); } System.out.println(Configuration.SEPARATOR); }
@Override public void filter(ContainerRequestContext requestContext) throws IOException { // Only allow requests on the admin interfaces Object listenAddressName = requestContext.getProperty(LISTEN_ADDRESS_NAME_ATTRIBUTE); if (listenAddressName == null || !listenAddressName.equals(ServerConfig.ADMIN_ADDRESS)) { throw new NotFoundException(); } // Only allow admin users Boolean admin = (Boolean) request.getAttribute("admin"); if (admin == null || !admin) { throw new ForbiddenException(); } }
@Transactional public Result<Repository> createRepository(String userName, RepositoryForm repositoryForm) { if (!repositoryForm.getOwner().equals(userName)) { throw new ForbiddenException(); } Repository check = emProvider.get().find(Repository.class, new RepositoryPK(userName, repositoryForm.getName())); if (check != null) { return Result.error("already exists"); } Repository repository = new Repository(); repository.setPk(new RepositoryPK(userName, repositoryForm.getName())); repository.setPrivateRepo(repositoryForm.isPrivateRepo()); repository.setDescription(repositoryForm.getDescription()); emProvider.get().persist(repository); gitOperation.init(userName, repository.getPk().getRepositoryName(), repository.getDefaultBranch()); return Result.success(repository); }
@Override public void filter(ContainerRequestContext requestContext) throws IOException { Repo repo = ResourceUtils.getAnnotation(resourceInfo, Repo.class).orElse(null); if (repo != null) { String owner = uriInfo.getPathParameters().getFirst(repo.ownerPath()); String repoName = uriInfo.getPathParameters().getFirst(repo.repositoryPath()); if (owner == null || repoName == null) { throw new NotFoundException(); } Optional<RepositoryContext> repoContext = repositoryController.getContext(new RepositoryPK(owner, repoName)); if (!repoContext.isPresent()) { throw new NotFoundException(); } servletRequest.setAttribute(RepositoryContext.ATTR_NAME, repoContext.get()); if (!repoContext.get().canAccess(repo.collaboratorOnly())) { throw new ForbiddenException("collaborator-only"); } } }
@GET @Produces(MediaType.APPLICATION_JSON) public java.util.List<Reminder> getRemindersInList(@PathParam("listid") long listId) { List list = em.find(List.class, listId); if (list == null) { throw new NotFoundException(); } // Only admins can read another user's reminders. if (!list.getOwner().getUsername().equals(context.getUserPrincipal().getName()) && !context.isUserInRole(Role.ADMINISTRATOR.name())) { throw new ForbiddenException(); } TypedQuery<Reminder> q = em.createNamedQuery("Reminder.findByList", Reminder.class).setParameter("list", list); return q.getResultList(); }
@POST @Consumes(MediaType.APPLICATION_JSON) public Response addReminderToList(@PathParam("listid") long listId, Reminder reminder) { List list = em.find(List.class, listId); if (list == null) { throw new NotFoundException(); } // Only admins can add reminders to another user's lists. if (!list.getOwner().getUsername().equals(context.getUserPrincipal().getName()) && !context.isUserInRole(Role.ADMINISTRATOR.name())) { throw new ForbiddenException(); } reminder.setList(list); Set<ConstraintViolation<Reminder>> violations = validator.validate(reminder); if (!violations.isEmpty()) { throw new BadRequestException(mergeMessages(violations)); } em.persist(reminder); return Response.created(URI.create("/lists/" + listId + "/reminders/" + reminder.getId())).build(); }
@GET @Path("{reminderid}") @Produces(MediaType.APPLICATION_JSON) public Reminder getReminder(@PathParam("listid") long listId, @PathParam("reminderid") long reminderId) { Reminder reminder = em.find(Reminder.class, reminderId); if (reminder == null || reminder.getList().getId() != listId) { throw new NotFoundException(); } // Only admins can read another user's reminders. if (!reminder.getList().getOwner().getUsername().equals(context.getUserPrincipal().getName()) && !context.isUserInRole(Role.ADMINISTRATOR.name())) { throw new ForbiddenException(); } return reminder; }
@DELETE @Path("{reminderid}") public void removeReminder(@PathParam("listid") long listId, @PathParam("reminderid") long reminderId) throws IOException { Reminder reminder = em.find(Reminder.class, reminderId); if (reminder == null || reminder.getList().getId() != listId) { throw new NotFoundException(); } // Only admins can delete another user's reminders. if (!reminder.getList().getOwner().getUsername().equals(context.getUserPrincipal().getName()) && !context.isUserInRole(Role.ADMINISTRATOR.name())) { throw new ForbiddenException(); } if (reminder.getImage() != null) { Files.deleteIfExists(IMAGES_BASE_DIR.resolve(reminder.getImage())); } em.remove(reminder); }
@PUT @Path("{reminderid}/image") @Consumes("image/jpeg") public void setImage(@PathParam("listid") long listId, @PathParam("reminderid") long reminderId, @HeaderParam("Content-Length") long fileSize, InputStream in) throws IOException { Reminder reminder = em.find(Reminder.class, reminderId); if (reminder == null || reminder.getList().getId() != listId) { throw new NotFoundException(); } // Only admins can update another user's images. if (!context.getUserPrincipal().getName().equals(reminder.getList().getOwner().getUsername()) && !context.isUserInRole(Role.ADMINISTRATOR.name())) { throw new ForbiddenException(); } // Make sure the file is not larger than the maximum allowed size. if (fileSize > 1024 * 1024 * MAX_IMAGE_SIZE_IN_MB) { throw new BadRequestException("REMINDER_IMAGE"); } // Save the image. By default, {reminderid}.jpg is used as the filename. Files.copy(in, IMAGES_BASE_DIR.resolve(reminder.getId() + ".jpg"), StandardCopyOption.REPLACE_EXISTING); reminder.setImage(reminder.getId() + ".jpg"); }
@DELETE @Path("{reminderid}/image") public void removeImage(@PathParam("listid") long listId, @PathParam("reminderid") long reminderId) throws IOException { Reminder reminder = em.find(Reminder.class, reminderId); if (reminder == null || reminder.getList().getId() != listId || reminder.getImage() == null) { throw new NotFoundException(); } // Only admins can delete another user's images. if (!context.getUserPrincipal().getName().equals(reminder.getList().getOwner().getUsername()) && !context.isUserInRole(Role.ADMINISTRATOR.name())) { throw new ForbiddenException(); } Files.deleteIfExists(IMAGES_BASE_DIR.resolve(reminder.getImage())); reminder.setImage(null); }
@DELETE @Path("{username}") public void removeUser(@PathParam("username") String username) throws IOException { User user = em.find(User.class, username); if (user == null) { throw new NotFoundException(); } if (!context.getUserPrincipal().getName().equals(username) && !context.isUserInRole(Role.ADMINISTRATOR.name())) { throw new ForbiddenException(); } TypedQuery<List> q = em.createNamedQuery("List.findByOwner", List.class).setParameter("owner", user); for (List list : q.getResultList()) { listsResource.removeList(list.getId()); } Files.deleteIfExists(IMAGES_BASE_DIR.resolve(username + ".png")); em.remove(user); }
@DELETE @Path("{username}/picture") public void removeProfilePicture(@PathParam("username") String username) throws IOException { User user = em.find(User.class, username); if (user == null) { throw new NotFoundException(); } if (!context.getUserPrincipal().getName().equals(username) && !context.isUserInRole(Role.ADMINISTRATOR.name())) { throw new ForbiddenException(); } Files.deleteIfExists(IMAGES_BASE_DIR.resolve(username + ".png")); // Clearing the profile picture will reset it to the default profile picture. user.setProfilePicture(null); }
@POST @Consumes(MediaType.APPLICATION_JSON) public Response addList(List list) { // If the list doesn't have an owner, set it to the current user. if (list.getOwner() == null) { list.setOwner(em.find(User.class, context.getUserPrincipal().getName())); } // Only admins can create lists for other users. if (!list.getOwner().getUsername().equals(context.getUserPrincipal().getName()) && !context.isUserInRole(Role.ADMINISTRATOR.name())) { throw new ForbiddenException(); } Set<ConstraintViolation<List>> violations = validator.validate(list); if (!violations.isEmpty()) { throw new BadRequestException(mergeMessages(violations)); } em.persist(list); return Response.created(URI.create("/lists/" + list.getId())).build(); }
@GET @Path("{listid}") @Produces(MediaType.APPLICATION_JSON) public List getList(@PathParam("listid") long id) { List list = em.find(List.class, id); if (list == null) { throw new NotFoundException(); } // Only admins can read other user's lists. if (!list.getOwner().getUsername().equals(context.getUserPrincipal().getName()) && !context.isUserInRole(Role.ADMINISTRATOR.name())) { throw new ForbiddenException(); } return list; }
@DELETE @Path("{listid}") public void removeList(@PathParam("listid") long id) throws IOException { List list = em.find(List.class, id); if (list == null) { throw new NotFoundException(); } // Only admins can delete other user's lists. if (!list.getOwner().getUsername().equals(context.getUserPrincipal().getName()) && !context.isUserInRole(Role.ADMINISTRATOR.name())) { throw new ForbiddenException(); } TypedQuery<Reminder> q = em.createNamedQuery("Reminder.findByList", Reminder.class).setParameter("list", list); for (Reminder reminder : q.getResultList()) { remindersResource.removeReminder(list.getId(), reminder.getId()); } em.remove(list); }
@Override public User authenticate(final String username, final String password) { User user = null; for (User entry : USERS.values()) { if (username.equals(entry.getUsername())) { user = entry; } } if (user == null) { throw new NotFoundException(username); } if (!password.equals(user.getPassword())) { throw new ForbiddenException(); } return user; }
private Response submit(String id) { DataAccessRequest request = dataAccessRequestService.findById(id); boolean fromOpened = request.getStatus() == DataAccessRequest.Status.OPENED; boolean fromConditionallyApproved = request.getStatus() == DataAccessRequest.Status.CONDITIONALLY_APPROVED; if(fromOpened && !subjectAclService.isCurrentUser(request.getApplicant())) { // only applicant can submit an opened request throw new ForbiddenException(); } dataAccessRequestService.updateStatus(id, DataAccessRequest.Status.SUBMITTED); if (fromOpened || fromConditionallyApproved) { // applicant cannot edit, nor delete request anymore + status cannot be changed subjectAclService.removePermission("/data-access-request", "EDIT,DELETE", id); subjectAclService.removePermission("/data-access-request/" + id, "EDIT", "_status"); // data access officers can change the status of this request subjectAclService.addGroupPermission(Roles.MICA_DAO, "/data-access-request/" + id, "EDIT", "_status"); } return Response.noContent().build(); }
/** * {@inheritDoc} */ @Override public Response toResponse(final ForbiddenException exception) { if (L.isDebugEnabled()) { L.debug(R.getString("D-REST-JERSEY-MAPPER#0003")); } ErrorMessage error = ErrorMessages.create(exception) .code(ErrorCode.FORBIDDEN.code()) .resolve() .get(); L.warn(error.log(), exception); return Response.status(exception.getResponse().getStatusInfo()) .entity(error) .type(MediaType.APPLICATION_JSON) .build(); }
@Override public void filter(ContainerRequestContext request) throws IOException { Subject subject = SubjectContext.getSubject(system); LOGGER.trace("enter() {} - {}", subject, request.getUriInfo().getRequestUri()); if (subject.getPrincipal() == null) { throw new AuthenticationException("@Permissions", request); } Map<String, String> ctx = new LinkedHashMap<>(); for (String var : vars) { String val = request.getUriInfo().getPathParameters().getFirst(var); ctx.put(var, val == null ? "" : val); } Collection<String> resolved = new HashSet<>(); for (String permission : permissions) { for (Map.Entry<String, String> entry : ctx.entrySet()) { permission = permission.replace('{' + entry.getKey() + '}', entry.getValue()); } resolved.add(permission); } if (!subject.isPermitted(resolved)) { throw new ForbiddenException("Invalid permissions"); } }
@Override public void filter(ContainerRequestContext requestContext) throws IOException { if (!denyAll) { for (String role : rolesAllowed) { if (requestContext.getSecurityContext().isUserInRole(role)) { return; } } } boolean isApikeyExist = false; for (String apikeyHeader: AuthenticationFilter.API_KEY_HEADERS) { String value = requestContext.getHeaderString(apikeyHeader); if (value != null) { isApikeyExist = true; } } // If request doesn't contain any authentication header, make the browser pop up HTTP BASIC login window. if (!isApikeyExist && requestContext.getHeaderString(AuthenticationFilter.AUTHORIZATION_HEADER) == null) throw new WebApplicationException(Response.status(Status.UNAUTHORIZED).header("WWW-Authenticate", "Basic").build()); else throw new ForbiddenException(); }
@Test(expected = ForbiddenException.class) public void deleteNotManagedProject() throws Exception { final Subscription one = repository.findOne(getSubscription("gStack", IdentityResource.SERVICE_KEY)); final int project = one.getProject().getId(); Assert.assertEquals(3, repository.findAllByProject(project).size()); // Ensure LDAP cache is loaded CacheManager.getInstance().getCache("ldap").removeAll(); cache.getLdapData(); em.flush(); em.clear(); initSpringSecurityContext("alongchu"); resource.delete(one.getId()); }
@Test(expected = ForbiddenException.class) public void createOnTreePartialDn() { final DelegateOrgEditionVo vo = new DelegateOrgEditionVo(); vo.setName("cn=myDn"); vo.setType(DelegateType.TREE); vo.setReceiver("fdaugan"); resource.create(vo); }
@Test(expected = ForbiddenException.class) public void createOnUnkownCompany() { final DelegateOrgEditionVo vo = new DelegateOrgEditionVo(); vo.setName("any"); vo.setType(DelegateType.COMPANY); vo.setReceiver("fdaugan"); resource.create(vo); }
@Test(expected = ForbiddenException.class) public void updateForbiddenNotAdminDn() { initSpringSecurityContext("mlavoine"); final DelegateOrgEditionVo vo = new DelegateOrgEditionVo(); vo.setId(expected.getId()); vo.setName("Biz Agency"); vo.setReceiver("mlavoine"); vo.setType(DelegateType.GROUP); resource.update(vo); }
@Test(expected = ForbiddenException.class) public void updateInvisibleDelegateCompany() { initSpringSecurityContext("mtuyer"); final int id = em.createQuery("SELECT id FROM DelegateOrg WHERE receiver=:user AND dn=:dn", Integer.class).setParameter("user", "mtuyer") .setParameter("dn", "ou=fonction,ou=groups,dc=sample,dc=com").getSingleResult(); final DelegateOrgEditionVo vo = new DelegateOrgEditionVo(); vo.setId(id); vo.setName("socygan"); vo.setReceiver("mtuyer"); vo.setType(DelegateType.COMPANY); resource.update(vo); }
@Test(expected = ForbiddenException.class) public void updateForbiddenInvalidDelegateType() { initSpringSecurityContext("mtuyer"); final DelegateOrgEditionVo vo = new DelegateOrgEditionVo(); vo.setId(expected.getId()); vo.setName("ing"); vo.setReceiver("mtuyer"); vo.setType(DelegateType.GROUP); resource.update(vo); }
@Test(expected = ForbiddenException.class) public void updateForbiddenInvalidDelegateTree() { initSpringSecurityContext("mtuyer"); final int id = em.createQuery("SELECT id FROM DelegateOrg WHERE receiver=:user AND dn=:dn", Integer.class).setParameter("user", "mtuyer") .setParameter("dn", "ou=fonction,ou=groups,dc=sample,dc=com").getSingleResult(); final DelegateOrgEditionVo vo = new DelegateOrgEditionVo(); vo.setId(id); vo.setName("ou=z,ou=groups,dc=sample,dc=com"); vo.setReceiver("mtuyer"); vo.setType(DelegateType.TREE); resource.update(vo); }
@Test(expected = ForbiddenException.class) public void deleteNotAdmin() { initSpringSecurityContext("someone"); final int id = em.createQuery("SELECT id FROM DelegateOrg WHERE receiver=:user AND name=:name", Integer.class) .setParameter("user", "someone").setParameter("name", "dig rha").getSingleResult(); resource.delete(id); }
private void verifyCanAppend(final Set<IRI> modes, final Session session, final String path) { if (!modes.contains(ACL.Append) && !modes.contains(ACL.Write)) { LOGGER.warn("User: {} cannot Append to {}", session.getAgent(), path); if (Trellis.AnonymousAgent.equals(session.getAgent())) { throw new NotAuthorizedException(challenges.get(0), challenges.subList(1, challenges.size()).toArray()); } throw new ForbiddenException(); } }