javax.ws.rs.ForbiddenException Java Examples
The following examples show how to use
javax.ws.rs.ForbiddenException.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: VaultMock.java From component-runtime with Apache License 2.0 | 6 votes |
@POST @Path("decrypt/{tenant}") public VaultService.DecryptResponse decrypt(@HeaderParam("X-Vault-Token") final String token, @PathParam("tenant") final String tenant, final VaultService.DecryptRequest request) { if (!"client-test-token".equals(token) || tenant == null || tenant.isEmpty() || "x-talend-tenant-id".equals(tenant)) { throw new ForbiddenException(); } if (!"vault:v1:hcccVPODe9oZpcr/sKam8GUrbacji8VkuDRGfuDt7bg7VA==" .equals(request.getBatchInput().iterator().next().getCiphertext())) { throw new BadRequestException(); } final VaultService.DecryptResult result = new VaultService.DecryptResult(); result.setPlaintext(Base64.getEncoder().encodeToString("test".getBytes(StandardCharsets.UTF_8))); final VaultService.DecryptData data = new VaultService.DecryptData(); data.setBatchResults(singletonList(result)); final VaultService.DecryptResponse response = new VaultService.DecryptResponse(); response.setData(data); return response; }
Example #2
Source File: SyncopeConsoleSession.java From syncope with Apache License 2.0 | 6 votes |
@Override public void onException(final Exception e) { Throwable root = ExceptionUtils.getRootCause(e); String message = root.getMessage(); if (root instanceof SyncopeClientException) { SyncopeClientException sce = (SyncopeClientException) root; if (!sce.isComposite()) { message = sce.getElements().stream().collect(Collectors.joining(", ")); } } else if (root instanceof AccessControlException || root instanceof ForbiddenException) { Error error = StringUtils.containsIgnoreCase(message, "expired") ? Error.SESSION_EXPIRED : Error.AUTHORIZATION; message = getApplication().getResourceSettings().getLocalizer(). getString(error.key(), null, null, null, null, error.fallback()); } else if (root instanceof BadRequestException || root instanceof WebServiceException) { message = getApplication().getResourceSettings().getLocalizer(). getString(Error.REST.key(), null, null, null, null, Error.REST.fallback()); } message = getApplication().getResourceSettings().getLocalizer(). getString(message, null, null, null, null, message); error(message); }
Example #3
Source File: WebAcFilterTest.java From trellis with Apache License 2.0 | 6 votes |
@Test void testFilterCustomAppend() { final Set<IRI> modes = new HashSet<>(); when(mockContext.getMethod()).thenReturn("APPEND"); when(mockWebAcService.getAuthorizedModes(any(IRI.class), any(Session.class))) .thenReturn(new AuthorizedModes(effectiveAcl, modes)); final WebAcFilter filter = new WebAcFilter(); filter.setAccessService(mockWebAcService); modes.add(ACL.Append); assertDoesNotThrow(() -> filter.filter(mockContext), "Unexpected exception after adding Append ability!"); modes.add(ACL.Write); assertDoesNotThrow(() -> filter.filter(mockContext), "Unexpected exception after adding Write ability!"); modes.remove(ACL.Append); assertDoesNotThrow(() -> filter.filter(mockContext), "Unexpected exception after removing Append ability!"); modes.clear(); assertThrows(NotAuthorizedException.class, () -> filter.filter(mockContext), "No expception thrown when not authorized!"); when(mockContext.getSecurityContext()).thenReturn(mockSecurityContext); assertThrows(ForbiddenException.class, () -> filter.filter(mockContext), "No exception thrown!"); }
Example #4
Source File: WebAcFilterTest.java From trellis with Apache License 2.0 | 6 votes |
@Test void testFilterControl() { final Set<IRI> modes = new HashSet<>(); when(mockContext.getMethod()).thenReturn("GET"); when(mockWebAcService.getAuthorizedModes(any(IRI.class), any(Session.class))) .thenReturn(new AuthorizedModes(effectiveAcl, modes)); final WebAcFilter filter = new WebAcFilter(); filter.setAccessService(mockWebAcService); modes.add(ACL.Read); assertDoesNotThrow(() -> filter.filter(mockContext), "Unexpected exception after adding Read ability!"); when(mockContext.getHeaderString("Prefer")) .thenReturn("return=representation; include=\"" + Trellis.PreferAudit.getIRIString() + "\""); assertThrows(NotAuthorizedException.class, () -> filter.filter(mockContext), "No expception thrown when not authorized!"); modes.add(ACL.Control); assertDoesNotThrow(() -> filter.filter(mockContext), "Unexpected exception after adding Control ability!"); modes.clear(); when(mockContext.getSecurityContext()).thenReturn(mockSecurityContext); assertThrows(ForbiddenException.class, () -> filter.filter(mockContext), "No exception thrown!"); }
Example #5
Source File: WebAcFilterTest.java From trellis with Apache License 2.0 | 6 votes |
@Test void testFilterControl2() { final Set<IRI> modes = new HashSet<>(); when(mockContext.getMethod()).thenReturn("GET"); when(mockWebAcService.getAuthorizedModes(any(IRI.class), any(Session.class))) .thenReturn(new AuthorizedModes(effectiveAcl, modes)); final WebAcFilter filter = new WebAcFilter(); filter.setAccessService(mockWebAcService); modes.add(ACL.Read); assertDoesNotThrow(() -> filter.filter(mockContext), "Unexpected exception after adding Read ability!"); when(mockQueryParams.getOrDefault(eq("ext"), eq(emptyList()))).thenReturn(singletonList("acl")); assertThrows(NotAuthorizedException.class, () -> filter.filter(mockContext), "No expception thrown when not authorized!"); modes.add(ACL.Control); assertDoesNotThrow(() -> filter.filter(mockContext), "Unexpected exception after adding Control ability!"); modes.clear(); when(mockContext.getSecurityContext()).thenReturn(mockSecurityContext); assertThrows(ForbiddenException.class, () -> filter.filter(mockContext), "No exception thrown!"); }
Example #6
Source File: ExportResourceProvider.java From keycloak-export with GNU Affero General Public License v3.0 | 6 votes |
@GET @Path("realm") @Produces(MediaType.APPLICATION_JSON) public RealmRepresentation exportRealm(@Context final HttpHeaders headers, @Context final UriInfo uriInfo) { //retrieving the realm should be done before authentication // authentication overrides the value with master inside the context // this is done this way to avoid changing the copied code below (authenticateRealmAdminRequest) RealmModel realm = session.getContext().getRealm(); AdminAuth adminAuth = authenticateRealmAdminRequest(headers, uriInfo); RealmManager realmManager = new RealmManager(session); RoleModel roleModel = adminAuth.getRealm().getRole(AdminRoles.ADMIN); AdminPermissionEvaluator realmAuth = AdminPermissions.evaluator(session, realm, adminAuth); if (roleModel != null && adminAuth.getUser().hasRole(roleModel) && adminAuth.getRealm().equals(realmManager.getKeycloakAdminstrationRealm()) && realmAuth.realm().canManageRealm()) { RealmRepresentation realmRep = ExportUtils.exportRealm(session, realm, true, true); //correct users if (realmRep.getUsers() != null) { setCorrectCredentials(realmRep.getUsers(), realm); } return realmRep; } else { throw new ForbiddenException(); } }
Example #7
Source File: SubmissionUtils.java From judgels with GNU General Public License v2.0 | 6 votes |
public static void checkGradingLanguageAllowed( String gradingEngine, String gradingLanguage, LanguageRestriction restriction) { boolean allowed; if (gradingEngine.startsWith(OutputOnlyOverrides.KEY)) { allowed = gradingLanguage.startsWith(OutputOnlyOverrides.KEY); } else if (gradingLanguage.startsWith(OutputOnlyOverrides.KEY)) { allowed = gradingEngine.startsWith(OutputOnlyOverrides.KEY); } else { allowed = restriction.isAllowedAll() || restriction.getAllowedLanguages().contains(gradingLanguage); } if (!allowed) { throw new ForbiddenException("Grading language " + gradingLanguage + " is not allowed"); } }
Example #8
Source File: WebAcFilterTest.java From trellis with Apache License 2.0 | 6 votes |
@Test void testFilterCustomRead() { final Set<IRI> modes = new HashSet<>(); when(mockContext.getMethod()).thenReturn("READ"); when(mockWebAcService.getAuthorizedModes(any(IRI.class), any(Session.class))) .thenReturn(new AuthorizedModes(effectiveAcl, modes)); final WebAcFilter filter = new WebAcFilter(); filter.setAccessService(mockWebAcService); modes.add(ACL.Read); assertDoesNotThrow(() -> filter.filter(mockContext), "Unexpected exception after adding Read ability!"); modes.clear(); assertThrows(NotAuthorizedException.class, () -> filter.filter(mockContext), "No expception thrown when not authorized!"); when(mockContext.getSecurityContext()).thenReturn(mockSecurityContext); assertThrows(ForbiddenException.class, () -> filter.filter(mockContext), "No exception thrown!"); }
Example #9
Source File: MCRRestAuthorizationFilter.java From mycore with GNU General Public License v3.0 | 6 votes |
private void checkDetailLevel(ContainerRequestContext requestContext, String... detail) throws ForbiddenException { MCRRequestScopeACL aclProvider = MCRRequestScopeACL.getInstance(requestContext); List<String> missedPermissions = Stream.of(detail) .map(d -> "rest-detail-" + d) .filter(d -> MCRAccessManager.hasRule(MCRAccessControlSystem.POOL_PRIVILEGE_ID, d)) .filter(d -> !aclProvider.checkPermission(d)) .collect(Collectors.toList()); if (!missedPermissions.isEmpty()) { throw MCRErrorResponse.fromStatus(Response.Status.FORBIDDEN.getStatusCode()) .withErrorCode(MCRErrorCodeConstants.API_NO_PERMISSION) .withMessage("REST-API action is not allowed.") .withDetail("Check access right(s) '" + missedPermissions + "' on " + MCRAccessControlSystem.POOL_PRIVILEGE_ID + "'!") .toException(); } }
Example #10
Source File: WebAcFilterTest.java From trellis with Apache License 2.0 | 6 votes |
@Test void testFilterReadSlashPath() { final Set<IRI> modes = new HashSet<>(); when(mockContext.getMethod()).thenReturn("GET"); when(mockWebAcService.getAuthorizedModes(any(IRI.class), any(Session.class))) .thenReturn(new AuthorizedModes(effectiveAcl, modes)); when(mockUriInfo.getPath()).thenReturn("container/"); final WebAcFilter filter = new WebAcFilter(); filter.setAccessService(mockWebAcService); modes.add(ACL.Read); assertDoesNotThrow(() -> filter.filter(mockContext), "Unexpected exception after adding Read ability!"); modes.clear(); assertThrows(NotAuthorizedException.class, () -> filter.filter(mockContext), "No expception thrown when not authorized!"); when(mockContext.getSecurityContext()).thenReturn(mockSecurityContext); assertThrows(ForbiddenException.class, () -> filter.filter(mockContext), "No exception thrown!"); }
Example #11
Source File: UserSelfITCase.java From syncope with Apache License 2.0 | 6 votes |
@Test public void create() { assumeTrue(FlowableDetector.isFlowableEnabledForUserWorkflow(syncopeService)); // 1. self-registration as admin: failure try { userSelfService.create(UserITCase.getUniqueSample("[email protected]")); fail("This should not happen"); } catch (ForbiddenException e) { assertNotNull(e); } // 2. self-registration as anonymous: works SyncopeClient anonClient = clientFactory.create(); UserTO self = anonClient.getService(UserSelfService.class). create(UserITCase.getUniqueSample("[email protected]")). readEntity(new GenericType<ProvisioningResult<UserTO>>() { }).getEntity(); assertNotNull(self); assertEquals("createApproval", self.getStatus()); }
Example #12
Source File: RepositoriesServiceTest.java From archiva with Apache License 2.0 | 6 votes |
@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; } }
Example #13
Source File: RolesAllowedFilter.java From smallrye-jwt with Apache License 2.0 | 6 votes |
@Override public void filter(ContainerRequestContext requestContext) { SecurityContext securityContext = requestContext.getSecurityContext(); boolean isForbidden; if (allRolesAllowed) { isForbidden = securityContext.getUserPrincipal() == null; } else { isForbidden = allowedRoles.stream().noneMatch(securityContext::isUserInRole); } if (isForbidden) { if (requestContext.getSecurityContext().getUserPrincipal() == null) { throw new NotAuthorizedException("Bearer"); } else { throw new ForbiddenException(); } } }
Example #14
Source File: VaultMock.java From component-runtime with Apache License 2.0 | 6 votes |
@POST @Path("login") public VaultService.AuthResponse login(final VaultService.AuthRequest request) { if (!"Test-Role".equals(request.getRoleId()) || !"Test-Secret".equals(request.getSecretId())) { throw new ForbiddenException(); } final VaultService.Auth auth = new VaultService.Auth(); auth.setClientToken("client-test-token"); auth.setRenewable(true); auth.setLeaseDuration(800000); final VaultService.AuthResponse response = new VaultService.AuthResponse(); response.setAuth(auth); return response; }
Example #15
Source File: PingServiceTest.java From archiva with Apache License 2.0 | 6 votes |
@Test( expected = ForbiddenException.class ) public void pingWithAuthzFailed() throws Exception { try { PingResult res = getPingService().pingWithAuthz(); fail( "not in exception" ); } catch ( ForbiddenException e ) { assertEquals( 403, e.getResponse().getStatus() ); throw e; } }
Example #16
Source File: ResourceObjectPermissionCheckerTest.java From cloudbreak with Apache License 2.0 | 6 votes |
@Test public void testCheckPermissionsWithResourceObjectWhenOtherExceptionOccurs() { when(commonPermissionCheckingUtils.getParameter(any(), any(), any(), any())).thenReturn(new ResourceObjectWithNameAnnotation()); when(resourceBasedCrnProvider.getResourceCrnByResourceName(anyString())).thenReturn(RESOURCE_CRN); doThrow(new ForbiddenException("some error")).when(commonPermissionCheckingUtils) .checkPermissionForUserOnResource(any(), anyString(), anyString()); thrown.expect(ForbiddenException.class); thrown.expectMessage("some error"); underTest.checkPermissions(getAnnotation(), USER_CRN, null, null, 0L); verify(commonPermissionCheckingUtils).proceed(any(), any(), anyLong()); verify(commonPermissionCheckingUtils).getParameter(any(), any(), eq(ResourceObject.class), eq(Object.class)); verify(commonPermissionCheckingUtils, times(0)).checkPermissionForUser(any(), anyString()); verify(commonPermissionCheckingUtils).checkPermissionForUserOnResource(eq(AuthorizationResourceAction.EDIT_CREDENTIAL), eq(USER_CRN), eq(RESOURCE_CRN)); verify(resourceBasedCrnProvider).getResourceCrnByResourceName(eq("resource")); }
Example #17
Source File: QueryResource.java From presto with Apache License 2.0 | 6 votes |
@ResourceSecurity(AUTHENTICATED_USER) @DELETE @Path("{queryId}") public void cancelQuery(@PathParam("queryId") QueryId queryId, @Context HttpServletRequest servletRequest, @Context HttpHeaders httpHeaders) { requireNonNull(queryId, "queryId is null"); try { BasicQueryInfo queryInfo = dispatchManager.getQueryInfo(queryId); checkCanKillQueryOwnedBy(extractAuthorizedIdentity(servletRequest, httpHeaders, accessControl, groupProvider), queryInfo.getSession().getUser(), accessControl); dispatchManager.cancelQuery(queryId); } catch (AccessDeniedException e) { throw new ForbiddenException(); } catch (NoSuchElementException ignored) { } }
Example #18
Source File: UiQueryResource.java From presto with Apache License 2.0 | 6 votes |
@ResourceSecurity(WEB_UI) @GET @Path("{queryId}") public Response getQueryInfo(@PathParam("queryId") QueryId queryId, @Context HttpServletRequest servletRequest, @Context HttpHeaders httpHeaders) { requireNonNull(queryId, "queryId is null"); Optional<QueryInfo> queryInfo = dispatchManager.getFullQueryInfo(queryId); if (queryInfo.isPresent()) { try { checkCanViewQueryOwnedBy(extractAuthorizedIdentity(servletRequest, httpHeaders, accessControl, groupProvider), queryInfo.get().getSession().getUser(), accessControl); return Response.ok(queryInfo.get()).build(); } catch (AccessDeniedException e) { throw new ForbiddenException(); } } return Response.status(Status.GONE).build(); }
Example #19
Source File: QueryResource.java From presto with Apache License 2.0 | 6 votes |
@ResourceSecurity(AUTHENTICATED_USER) @GET @Path("{queryId}") public Response getQueryInfo(@PathParam("queryId") QueryId queryId, @Context HttpServletRequest servletRequest, @Context HttpHeaders httpHeaders) { requireNonNull(queryId, "queryId is null"); Optional<QueryInfo> queryInfo = dispatchManager.getFullQueryInfo(queryId); if (queryInfo.isEmpty()) { return Response.status(Status.GONE).build(); } try { checkCanViewQueryOwnedBy(extractAuthorizedIdentity(servletRequest, httpHeaders, accessControl, groupProvider), queryInfo.get().getSession().getUser(), accessControl); return Response.ok(queryInfo.get()).build(); } catch (AccessDeniedException e) { throw new ForbiddenException(); } }
Example #20
Source File: EnvironmentCreateTest.java From cloudbreak with Apache License 2.0 | 5 votes |
@Test(dataProvider = TEST_CONTEXT_WITH_MOCK) @Description( given = "there is a running env service", when = "valid create environment request is sent", then = "environment should be created but unauthorized users should not be able to access it") public void testCreateEnvironment(TestContext testContext) { MockedTestContext mockedTestContext = mockCmForFreeipa(testContext); useRealUmsUser(testContext, AuthUserKeys.MGMT_CONSOLE_ADMIN_A); testContext .given(CredentialTestDto.class) .when(credentialTestClient.create()) .given(EnvironmentTestDto.class) .withCreateFreeIpa(false) .when(environmentTestClient.create()) .await(EnvironmentStatus.AVAILABLE) // testing unauthorized calls for environment .when(environmentTestClient.describe(), RunningParameter.who(Actor.useRealUmsUser(AuthUserKeys.MGMT_CONSOLE_ADMIN_B))) .expect(ForbiddenException.class, RunningParameter.expectedMessage("You have no right to perform environments/describeEnvironment on resource crn:cdp.*") .withKey("EnvironmentGetAction")) .when(environmentTestClient.describe(), RunningParameter.who(Actor.useRealUmsUser(AuthUserKeys.ZERO_RIGHTS))) .expect(ForbiddenException.class, RunningParameter.expectedMessage("You have no right to perform environments/describeEnvironment on resource crn:cdp.*") .withKey("EnvironmentGetAction")); testFreeipaCreation(testContext, mockedTestContext); testContext .given(EnvironmentTestDto.class) .when(environmentTestClient.delete()) .awaitForFlow(RunningParameter.key("EnvironmentDeleteAction")) .validate(); }
Example #21
Source File: CorsFilterTest.java From jrestless with Apache License 2.0 | 5 votes |
@Test public void actualRequestFilter_InvalidOriginGiven_CorsFails() throws IOException { CorsFilter filter = new CorsFilter.Builder() .allowOrigin(DEFAULT_HOST) .build(); ContainerRequestContext request = createActualRequestMock(DEFAULT_HOST, DEFAULT_ORIGIN, HttpMethod.GET); assertThrows(ForbiddenException.class, () -> filter.filter(request)); }
Example #22
Source File: AutomationClientAuthFactoryTest.java From keywhiz with Apache License 2.0 | 5 votes |
@Test(expected = ForbiddenException.class) public void automationClientRejectsClientsWithoutAutomation() { Client clientWithoutAutomation = new Client(3423, "clientWithoutAutomation", null, null, null, null, null, null, null, null, true, false ); when(securityContext.getUserPrincipal()).thenReturn( SimplePrincipal.of("CN=clientWithoutAutomation")); when(clientDAO.getClientByName("clientWithoutAutomation")) .thenReturn(Optional.of(clientWithoutAutomation)); factory.provide(request); }
Example #23
Source File: MCRForbiddenExceptionMapper.java From mycore with GNU General Public License v3.0 | 5 votes |
public Response toResponse(ForbiddenException ex) { String userID = MCRSessionMgr.getCurrentSession().getUserInformation().getUserID(); if (userID.equals(MCRSystemUserInformation.getGuestInstance().getUserID())) { LogManager.getLogger().warn("Guest detected"); return Response.fromResponse(ex.getResponse()) .status(Response.Status.UNAUTHORIZED) .header(HttpHeaders.WWW_AUTHENTICATE, MCRRestAPIUtil.getWWWAuthenticateHeader("Basic", null, app)) .build(); } return ex.getResponse(); }
Example #24
Source File: NetworkResource.java From batfish with Apache License 2.0 | 5 votes |
/** Check if {@code network} exists and {@code apiKey} has access to it. */ private static void checkAccessToNetwork(String apiKey, String network) { if (!Main.getWorkMgr().checkNetworkExists(network)) { throw new NotFoundException(String.format("Network '%s' does not exist", network)); } if (!Main.getAuthorizer().isAccessibleNetwork(apiKey, network, false)) { throw new ForbiddenException( String.format("network '%s' is not accessible by the api key: %s", network, apiKey)); } }
Example #25
Source File: KeyResourceImpl.java From authlib-agent with MIT License | 5 votes |
@Override public byte[] getEncodedKey() { if (!allowDownloadPrivateKey) { throw new ForbiddenException("It is not allowed to download the private key"); } RSAPrivateKey key = signatureService.getKey(); return key == null ? new byte[0] : key.getEncoded(); }
Example #26
Source File: WebAcFilter.java From trellis with Apache License 2.0 | 5 votes |
protected void verifyCanWrite(final Set<IRI> modes, final Session session, final String path) { if (!modes.contains(ACL.Write)) { LOGGER.warn("User: {} cannot Write 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(); } LOGGER.debug("User: {} can write to {}", session.getAgent(), path); }
Example #27
Source File: WebAcFilter.java From trellis with Apache License 2.0 | 5 votes |
protected 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(); } LOGGER.debug("User: {} can append to {}", session.getAgent(), path); }
Example #28
Source File: WebAcFilter.java From trellis with Apache License 2.0 | 5 votes |
protected void verifyCanControl(final Set<IRI> modes, final Session session, final String path) { if (!modes.contains(ACL.Control)) { LOGGER.warn("User: {} cannot Control {}", session.getAgent(), path); if (Trellis.AnonymousAgent.equals(session.getAgent())) { throw new NotAuthorizedException(challenges.get(0), challenges.subList(1, challenges.size()).toArray()); } throw new ForbiddenException(); } LOGGER.debug("User: {} can control {}", session.getAgent(), path); }
Example #29
Source File: SecretDeliveryResource.java From keywhiz with Apache License 2.0 | 5 votes |
/** * Retrieve Secret by name * * @param secretName the name of the Secret to retrieve * @param client the client performing the retrieval * @return the secret with the specified name, if present and accessible to the client * * responseMessage 200 Found and retrieved Secret with given name * responseMessage 403 Secret is not assigned to Client * responseMessage 404 Secret with given name not found * responseMessage 500 Secret response could not be generated for given Secret */ @Timed @ExceptionMetered @GET public SecretDeliveryResponse getSecret(@NotEmpty @PathParam("secretName") String secretName, @Auth Client client) { Optional<SanitizedSecret> sanitizedSecret = aclDAO.getSanitizedSecretFor(client, secretName); Optional<Secret> secret = secretController.getSecretByName(secretName); if (!sanitizedSecret.isPresent()) { boolean clientExists = clientDAO.getClientByName(client.getName()).isPresent(); boolean secretExists = secret.isPresent(); if (clientExists && secretExists) { throw new ForbiddenException(format("Access denied: %s at '%s' by '%s'", client.getName(), "/secret/" + secretName, client)); } else { if (clientExists) { logger.info("Client {} requested unknown secret {}", client.getName(), secretName); } throw new NotFoundException(); } } logger.info("Client {} granted access to {}.", client.getName(), secretName); try { return SecretDeliveryResponse.fromSecret(secret.get()); } catch (IllegalArgumentException e) { logger.error(format("Failed creating response for secret %s", secretName), e); throw new InternalServerErrorException(); } }
Example #30
Source File: WebAcFilter.java From trellis with Apache License 2.0 | 5 votes |
protected void verifyCanRead(final Set<IRI> modes, final Session session, final String path) { if (!modes.contains(ACL.Read)) { LOGGER.warn("User: {} cannot Read from {}", session.getAgent(), path); if (Trellis.AnonymousAgent.equals(session.getAgent())) { throw new NotAuthorizedException(challenges.get(0), challenges.subList(1, challenges.size()).toArray()); } throw new ForbiddenException(); } LOGGER.debug("User: {} can read {}", session.getAgent(), path); }