Search in sources :

Example 41 with NotFoundException

use of org.forgerock.json.resource.NotFoundException in project OpenAM by OpenRock.

the class UmaPolicyServiceImplTest method shouldCreateUmaPolicy.

@Test
@SuppressWarnings("unchecked")
public void shouldCreateUmaPolicy() throws Exception {
    //Given
    Context context = createContext();
    JsonValue policy = createUmaPolicyJson("RESOURCE_SET_ID");
    List<ResourceResponse> createdPolicies = new ArrayList<>();
    ResourceResponse createdPolicy1 = newResourceResponse("ID_1", "REVISION_1", createBackendSubjectOnePolicyJson());
    ResourceResponse createdPolicy2 = newResourceResponse("ID_1", "REVISION_1", createBackendSubjectTwoPolicyJson());
    createdPolicies.add(createdPolicy1);
    createdPolicies.add(createdPolicy2);
    Promise<Pair<QueryResponse, List<ResourceResponse>>, ResourceException> queryPromise = Promises.newExceptionPromise((ResourceException) new NotFoundException());
    setupQueries(queryPromise, createdPolicy1, createdPolicy2);
    Promise<List<ResourceResponse>, ResourceException> createPolicyPromise = newResultPromise(createdPolicies);
    given(policyResourceDelegate.createPolicies(eq(context), Matchers.<Set<JsonValue>>anyObject())).willReturn(createPolicyPromise);
    //When
    UmaPolicy umaPolicy = policyService.createPolicy(context, policy).getOrThrowUninterruptibly();
    //Then
    InOrder inOrder = inOrder(resourceDelegationFilter, policyResourceDelegate, resourceDelegationFilter);
    inOrder.verify(resourceDelegationFilter).beforeResourceShared(any(UmaPolicy.class));
    inOrder.verify(policyResourceDelegate).createPolicies(eq(context), anySetOf(JsonValue.class));
    inOrder.verify(resourceDelegationFilter).afterResourceShared(any(UmaPolicy.class));
    assertThat(umaPolicy.getId()).isEqualTo("RESOURCE_SET_ID");
    assertThat(umaPolicy.getRevision()).isNotNull();
    assertThat(umaPolicy.asJson().asMap()).hasSize(3).contains(entry("policyId", "RESOURCE_SET_ID"), entry("name", "NAME"));
    JsonValue permissions = umaPolicy.asJson().get("permissions");
    assertThat(permissions.asList()).hasSize(2);
    assertThat(permissions.get(0).asMap()).contains(entry("subject", "SUBJECT_ONE"));
    assertThat(permissions.get(0).get("scopes").asList()).containsOnly("SCOPE_A", "SCOPE_B");
    assertThat(permissions.get(1).asMap()).contains(entry("subject", "SUBJECT_TWO"));
    assertThat(permissions.get(1).get("scopes").asList()).containsOnly("SCOPE_A");
}
Also used : ClientContext(org.forgerock.services.context.ClientContext) RealmContext(org.forgerock.openam.rest.RealmContext) SubjectContext(org.forgerock.openam.rest.resource.SubjectContext) SSOTokenContext(org.forgerock.openam.rest.resource.SSOTokenContext) Context(org.forgerock.services.context.Context) InOrder(org.mockito.InOrder) JsonValue(org.forgerock.json.JsonValue) ArrayList(java.util.ArrayList) NotFoundException(org.forgerock.json.resource.NotFoundException) ResourceResponse(org.forgerock.json.resource.ResourceResponse) ResourceException(org.forgerock.json.resource.ResourceException) List(java.util.List) ArrayList(java.util.ArrayList) UmaPolicy(org.forgerock.openam.uma.UmaPolicy) Pair(org.forgerock.util.Pair) Test(org.testng.annotations.Test)

Example 42 with NotFoundException

use of org.forgerock.json.resource.NotFoundException in project OpenAM by OpenRock.

the class UmaLabelsStore method read.

/**
     * Reads a label from the underlying database.
     * @param realm The current realm.
     * @param username The user that owns the label.
     * @param id The id of the label.
     * @return The retrieved label details.
     * @throws ResourceException Thrown if the label cannot be read.
     */
public ResourceSetLabel read(String realm, String username, String id) throws ResourceException {
    try (Connection connection = getConnection()) {
        SearchResultEntry entry = connection.searchSingleEntry(LDAPRequests.newSingleEntrySearchRequest(getLabelDn(realm, username, id)));
        Set<String> resourceSets = new HashSet<>();
        final Attribute resourceSetAttribute = entry.getAttribute(RESOURCE_SET_ATTR);
        if (resourceSetAttribute != null) {
            for (ByteString resourceSetId : resourceSetAttribute) {
                resourceSets.add(resourceSetId.toString());
            }
        }
        return getResourceSetLabel(entry, resourceSets);
    } catch (LdapException e) {
        final ResultCode resultCode = e.getResult().getResultCode();
        if (resultCode.equals(ResultCode.NO_SUCH_OBJECT)) {
            throw new NotFoundException();
        }
        throw new InternalServerErrorException("Could not read", e);
    }
}
Also used : Attribute(org.forgerock.opendj.ldap.Attribute) ByteString(org.forgerock.opendj.ldap.ByteString) Connection(org.forgerock.opendj.ldap.Connection) NotFoundException(org.forgerock.json.resource.NotFoundException) InternalServerErrorException(org.forgerock.json.resource.InternalServerErrorException) ByteString(org.forgerock.opendj.ldap.ByteString) LdapException(org.forgerock.opendj.ldap.LdapException) ResultCode(org.forgerock.opendj.ldap.ResultCode) SearchResultEntry(org.forgerock.opendj.ldap.responses.SearchResultEntry) HashSet(java.util.HashSet)

Example 43 with NotFoundException

use of org.forgerock.json.resource.NotFoundException in project OpenAM by OpenRock.

the class TokenResource method deleteToken.

/**
     * Deletes the token with the provided token id.
     *
     * @param context The context.
     * @param tokenId The token id.
     * @param deleteRefreshToken Whether to delete associated refresh token, if token id is for an access token.
     * @return {@code Void} if the token has been deleted.
     */
private Promise<Void, ResourceException> deleteToken(Context context, String tokenId, boolean deleteRefreshToken) {
    try {
        AMIdentity uid = getUid(context);
        JsonValue token = tokenStore.read(tokenId);
        if (token == null) {
            if (debug.errorEnabled()) {
                debug.error("TokenResource :: DELETE : No token with ID, " + tokenId + " found to delete");
            }
            throw new NotFoundException("Token Not Found", null);
        }
        String username = getAttributeValue(token, USERNAME);
        if (username == null || username.isEmpty()) {
            if (debug.errorEnabled()) {
                debug.error("TokenResource :: DELETE : No username associated with " + "token with ID, " + tokenId + ".");
            }
            throw new PermanentException(HttpURLConnection.HTTP_NOT_FOUND, "Not Found", null);
        }
        String grantType = getAttributeValue(token, GRANT_TYPE);
        if (grantType != null && grantType.equalsIgnoreCase(CLIENT_CREDENTIALS)) {
            if (deleteRefreshToken) {
                deleteAccessTokensRefreshToken(token);
            }
            tokenStore.delete(tokenId);
        } else {
            String realm = getAttributeValue(token, REALM);
            AMIdentity uid2 = identityManager.getResourceOwnerIdentity(username, realm);
            if (uid.equals(uid2) || uid.equals(adminUserId)) {
                if (deleteRefreshToken) {
                    deleteAccessTokensRefreshToken(token);
                }
                tokenStore.delete(tokenId);
            } else {
                if (debug.errorEnabled()) {
                    debug.error("TokenResource :: DELETE : Only the resource owner or an administrator may perform " + "a delete on the token with ID, " + tokenId + ".");
                }
                throw new PermanentException(401, "Unauthorized", null);
            }
        }
        return newResultPromise(null);
    } catch (CoreTokenException e) {
        return new ServiceUnavailableException(e.getMessage(), e).asPromise();
    } catch (ResourceException e) {
        return e.asPromise();
    } catch (SSOException e) {
        debug.error("TokenResource :: DELETE : Unable to retrieve identity of the requesting user. Unauthorized.");
        return new PermanentException(401, "Unauthorized", e).asPromise();
    } catch (IdRepoException e) {
        debug.error("TokenResource :: DELETE : Unable to retrieve identity of the requesting user. Unauthorized.");
        return new PermanentException(401, "Unauthorized", e).asPromise();
    } catch (UnauthorizedClientException e) {
        debug.error("TokenResource :: DELETE : Requesting user is unauthorized.");
        return new PermanentException(401, "Unauthorized", e).asPromise();
    }
}
Also used : AMIdentity(com.sun.identity.idm.AMIdentity) PermanentException(org.forgerock.json.resource.PermanentException) UnauthorizedClientException(org.forgerock.oauth2.core.exceptions.UnauthorizedClientException) JsonValue(org.forgerock.json.JsonValue) IdRepoException(com.sun.identity.idm.IdRepoException) NotFoundException(org.forgerock.json.resource.NotFoundException) CoreTokenException(org.forgerock.openam.cts.exceptions.CoreTokenException) ResourceException(org.forgerock.json.resource.ResourceException) SSOException(com.iplanet.sso.SSOException) ServiceUnavailableException(org.forgerock.json.resource.ServiceUnavailableException)

Example 44 with NotFoundException

use of org.forgerock.json.resource.NotFoundException in project OpenAM by OpenRock.

the class TokenResource method getExpiryDate.

private String getExpiryDate(JsonValue token, Context context) throws CoreTokenException, InternalServerErrorException, NotFoundException {
    OAuth2ProviderSettings oAuth2ProviderSettings;
    final String realm = getAttributeValue(token, "realm");
    try {
        oAuth2ProviderSettings = oAuth2ProviderSettingsFactory.get(realm);
    } catch (org.forgerock.oauth2.core.exceptions.NotFoundException e) {
        throw new NotFoundException(e.getMessage());
    }
    try {
        if (token.isDefined("refreshToken")) {
            if (oAuth2ProviderSettings.issueRefreshTokensOnRefreshingToken()) {
                return getIndefinitelyString(context);
            } else {
                //Use refresh token expiry
                JsonValue refreshToken = tokenStore.read(getAttributeValue(token, "refreshToken"));
                long expiryTimeInMilliseconds = Long.parseLong(getAttributeValue(refreshToken, EXPIRE_TIME_KEY));
                if (expiryTimeInMilliseconds == -1) {
                    return getIndefinitelyString(context);
                }
                return getDateFormat(context).format(new Date(expiryTimeInMilliseconds));
            }
        } else {
            //Use access token expiry
            long expiryTimeInMilliseconds = Long.parseLong(getAttributeValue(token, EXPIRE_TIME_KEY));
            return getDateFormat(context).format(new Date(expiryTimeInMilliseconds));
        }
    } catch (ServerException | SMSException | SSOException e) {
        throw new InternalServerErrorException(e);
    }
}
Also used : ServerException(org.forgerock.oauth2.core.exceptions.ServerException) SMSException(com.sun.identity.sm.SMSException) JsonValue(org.forgerock.json.JsonValue) NotFoundException(org.forgerock.json.resource.NotFoundException) SSOException(com.iplanet.sso.SSOException) Date(java.util.Date) InternalServerErrorException(org.forgerock.json.resource.InternalServerErrorException) OAuth2ProviderSettings(org.forgerock.oauth2.core.OAuth2ProviderSettings)

Example 45 with NotFoundException

use of org.forgerock.json.resource.NotFoundException in project OpenAM by OpenRock.

the class IdentityServicesImpl method searchIdentityDetails.

/**
     * Searches the identity repository to find all identities that match the search criteria and returns them as a
     * list of identities.
     *
     * @param crestQuery A CREST Query object which will contain either a _queryId or a _queryFilter.
     * @param searchModifiers The search modifiers
     * @param admin Your SSO token.
     * @return a list of matching identities.
     * @throws ResourceException
     */
public List<IdentityDetails> searchIdentityDetails(CrestQuery crestQuery, Map<String, Set<String>> searchModifiers, SSOToken admin) throws ResourceException {
    try {
        String realm = "/";
        String objectType = "User";
        if (searchModifiers != null) {
            realm = attractValues("realm", searchModifiers, "/");
            objectType = attractValues("objecttype", searchModifiers, "User");
        }
        AMIdentityRepository repo = getRepo(admin, realm);
        IdType idType = getIdType(objectType);
        if (idType != null) {
            List<AMIdentity> identities = fetchAMIdentities(idType, crestQuery, true, repo, searchModifiers);
            List<IdentityDetails> result = new ArrayList<>();
            for (AMIdentity identity : identities) {
                result.add(convertToIdentityDetails(identity, null));
            }
            return result;
        }
        debug.error("IdentityServicesImpl.searchIdentities unsupported IdType " + objectType);
        throw new BadRequestException("searchIdentities: unsupported IdType " + objectType);
    } catch (IdRepoException e) {
        debug.error("IdentityServicesImpl.searchIdentities", e);
        throw new InternalServerErrorException(e.getMessage());
    } catch (SSOException e) {
        debug.error("IdentityServicesImpl.searchIdentities", e);
        throw new InternalServerErrorException(e.getMessage());
    } catch (ObjectNotFound e) {
        debug.error("IdentityServicesImpl.searchIdentities", e);
        throw new NotFoundException(e.getMessage());
    }
}
Also used : ArrayList(java.util.ArrayList) IdRepoException(com.sun.identity.idm.IdRepoException) NotFoundException(org.forgerock.json.resource.NotFoundException) SSOException(com.iplanet.sso.SSOException) IdType(com.sun.identity.idm.IdType) ObjectNotFound(com.sun.identity.idsvcs.ObjectNotFound) AMIdentity(com.sun.identity.idm.AMIdentity) AMIdentityRepository(com.sun.identity.idm.AMIdentityRepository) IdentityDetails(com.sun.identity.idsvcs.IdentityDetails) BadRequestException(org.forgerock.json.resource.BadRequestException) InternalServerErrorException(org.forgerock.json.resource.InternalServerErrorException)

Aggregations

NotFoundException (org.forgerock.json.resource.NotFoundException)69 ResourceException (org.forgerock.json.resource.ResourceException)43 SSOException (com.iplanet.sso.SSOException)42 JsonValue (org.forgerock.json.JsonValue)39 InternalServerErrorException (org.forgerock.json.resource.InternalServerErrorException)39 BadRequestException (org.forgerock.json.resource.BadRequestException)38 SMSException (com.sun.identity.sm.SMSException)34 ResourceResponse (org.forgerock.json.resource.ResourceResponse)27 ForbiddenException (org.forgerock.json.resource.ForbiddenException)26 IdRepoException (com.sun.identity.idm.IdRepoException)24 PermanentException (org.forgerock.json.resource.PermanentException)24 ConflictException (org.forgerock.json.resource.ConflictException)22 ServiceNotFoundException (com.sun.identity.sm.ServiceNotFoundException)21 NotSupportedException (org.forgerock.json.resource.NotSupportedException)18 CoreTokenException (org.forgerock.openam.cts.exceptions.CoreTokenException)17 IdentityDetails (com.sun.identity.idsvcs.IdentityDetails)16 RealmContext (org.forgerock.openam.rest.RealmContext)16 SSOToken (com.iplanet.sso.SSOToken)14 UnsupportedEncodingException (java.io.UnsupportedEncodingException)14 MessagingException (javax.mail.MessagingException)14