Search in sources :

Example 21 with Approval

use of org.cloudfoundry.identity.uaa.approval.Approval in project uaa by cloudfoundry.

the class ClientAdminEndpointsMockMvcTests method testAddUpdateDeleteClientsTxDeleteUnsuccessfulRollback.

@Test
void testAddUpdateDeleteClientsTxDeleteUnsuccessfulRollback() throws Exception {
    ClientDetailsModification[] details = new ClientDetailsModification[15];
    for (int i = 0; i < 5; i++) {
        details[i] = (ClientDetailsModification) createClient(adminToken, null, SECRET, Collections.singleton("password"));
        details[i].setRefreshTokenValiditySeconds(120);
        details[i].setAction(ClientDetailsModification.UPDATE);
    }
    for (int i = 5; i < 10; i++) {
        details[i] = (ClientDetailsModification) createClient(adminToken, null, SECRET, null);
        details[i].setAction(ClientDetailsModification.DELETE);
    }
    for (int i = 10; i < 15; i++) {
        details[i] = createBaseClient(null, null, null);
        details[i].setAction(ClientDetailsModification.ADD);
    }
    String userToken = testClient.getUserOAuthAccessToken(details[0].getClientId(), "secret", testUser.getUserName(), testPassword, "oauth.approvals");
    addApprovals(userToken, details[0].getClientId());
    Approval[] approvals = getApprovals(details[0].getClientId());
    assertEquals(3, approvals.length);
    String deleteId = details[5].getClientId();
    details[5].setClientId("unknown.client.id");
    MockHttpServletRequestBuilder modifyClientsPost = post("/oauth/clients/tx/modify").header("Authorization", "Bearer " + adminToken).accept(APPLICATION_JSON).contentType(APPLICATION_JSON).content(JsonUtils.writeValueAsString(details));
    ResultActions result = mockMvc.perform(modifyClientsPost);
    result.andExpect(status().isNotFound());
    details[5].setClientId(deleteId);
    for (int i = 0; i < 5; i++) {
        ClientDetails c = getClient(details[i].getClientId());
        assertNotNull(c);
        assertNull(c.getRefreshTokenValiditySeconds());
    }
    for (int i = 5; i < 10; i++) {
        ClientDetails c = getClient(details[i].getClientId());
        assertNotNull(c);
    }
    for (int i = 10; i < 15; i++) {
        ClientDetails c = getClient(details[i].getClientId());
        assertNull(c);
    }
    approvals = getApprovals(details[0].getClientId());
    assertEquals(3, approvals.length);
}
Also used : ClientDetails(org.springframework.security.oauth2.provider.ClientDetails) BaseClientDetails(org.springframework.security.oauth2.provider.client.BaseClientDetails) MockHttpServletRequestBuilder(org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder) ClientDetailsHelper.clientArrayFromString(org.cloudfoundry.identity.uaa.mock.util.ClientDetailsHelper.clientArrayFromString) ClientDetailsHelper.arrayFromString(org.cloudfoundry.identity.uaa.mock.util.ClientDetailsHelper.arrayFromString) ClientDetailsHelper.clientFromString(org.cloudfoundry.identity.uaa.mock.util.ClientDetailsHelper.clientFromString) ResultActions(org.springframework.test.web.servlet.ResultActions) Approval(org.cloudfoundry.identity.uaa.approval.Approval) ClientDetailsModification(org.cloudfoundry.identity.uaa.oauth.client.ClientDetailsModification) Test(org.junit.jupiter.api.Test)

Example 22 with Approval

use of org.cloudfoundry.identity.uaa.approval.Approval in project uaa by cloudfoundry.

the class ClientAdminEndpointsMockMvcTests method addApprovals.

private void addApprovals(String token, String clientId) throws Exception {
    Date oneMinuteAgo = new Date(System.currentTimeMillis() - 60000);
    Date expiresAt = new Date(System.currentTimeMillis() + 60000);
    Approval[] approvals = new Approval[] { new Approval().setUserId(null).setClientId(clientId).setScope("cloud_controller.read").setExpiresAt(expiresAt).setStatus(ApprovalStatus.APPROVED).setLastUpdatedAt(oneMinuteAgo), new Approval().setUserId(null).setClientId(clientId).setScope("openid").setExpiresAt(expiresAt).setStatus(ApprovalStatus.APPROVED).setLastUpdatedAt(oneMinuteAgo), new Approval().setUserId(null).setClientId(clientId).setScope("password.write").setExpiresAt(expiresAt).setStatus(ApprovalStatus.APPROVED).setLastUpdatedAt(oneMinuteAgo) };
    MockHttpServletRequestBuilder put = put("/approvals/" + clientId).header("Authorization", "Bearer " + token).accept(APPLICATION_JSON).contentType(APPLICATION_JSON).content(JsonUtils.writeValueAsString(approvals));
    mockMvc.perform(put).andExpect(status().isOk());
}
Also used : MockHttpServletRequestBuilder(org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder) Approval(org.cloudfoundry.identity.uaa.approval.Approval) Date(java.util.Date)

Example 23 with Approval

use of org.cloudfoundry.identity.uaa.approval.Approval in project uaa by cloudfoundry.

the class IdentityZoneEndpointsMockMvcTests method test_delete_zone_cleans_db.

@Test
void test_delete_zone_cleans_db() throws Exception {
    IdentityProviderProvisioning idpp = webApplicationContext.getBean(JdbcIdentityProviderProvisioning.class);
    ScimGroupProvisioning groupProvisioning = webApplicationContext.getBean(ScimGroupProvisioning.class);
    ScimUserProvisioning userProvisioning = webApplicationContext.getBean(ScimUserProvisioning.class);
    ScimGroupMembershipManager membershipManager = webApplicationContext.getBean(ScimGroupMembershipManager.class);
    ScimGroupExternalMembershipManager externalMembershipManager = webApplicationContext.getBean(ScimGroupExternalMembershipManager.class);
    ApprovalStore approvalStore = webApplicationContext.getBean(ApprovalStore.class);
    JdbcTemplate template = webApplicationContext.getBean(JdbcTemplate.class);
    String id = generator.generate();
    IdentityZone zone = createZone(id, HttpStatus.CREATED, identityClientToken, new IdentityZoneConfiguration());
    // create zone and clients
    BaseClientDetails client = new BaseClientDetails("limited-client", null, "openid", GRANT_TYPE_AUTHORIZATION_CODE, "uaa.resource");
    client.setClientSecret("secret");
    client.addAdditionalInformation(ClientConstants.ALLOWED_PROVIDERS, Collections.singletonList(UAA));
    client.addAdditionalInformation("foo", "bar");
    for (String url : Arrays.asList("", "/")) {
        mockMvc.perform(post("/identity-zones/" + zone.getId() + "/clients" + url).header("Authorization", "Bearer " + identityClientZonesReadToken).contentType(APPLICATION_JSON).accept(APPLICATION_JSON).content(JsonUtils.writeValueAsString(client))).andExpect(status().isForbidden());
    }
    // create client without token
    mockMvc.perform(post("/identity-zones/" + zone.getId() + "/clients").contentType(APPLICATION_JSON).accept(APPLICATION_JSON).content(JsonUtils.writeValueAsString(client))).andExpect(status().isUnauthorized());
    MvcResult result = mockMvc.perform(post("/identity-zones/" + zone.getId() + "/clients").header("Authorization", "Bearer " + identityClientToken).contentType(APPLICATION_JSON).accept(APPLICATION_JSON).content(JsonUtils.writeValueAsString(client))).andExpect(status().isCreated()).andReturn();
    BaseClientDetails created = JsonUtils.readValue(result.getResponse().getContentAsString(), BaseClientDetails.class);
    assertNull(created.getClientSecret());
    assertEquals("zones.write", created.getAdditionalInformation().get(ClientConstants.CREATED_WITH));
    assertEquals(Collections.singletonList(UAA), created.getAdditionalInformation().get(ClientConstants.ALLOWED_PROVIDERS));
    assertEquals("bar", created.getAdditionalInformation().get("foo"));
    // ensure that UAA provider is there
    assertNotNull(idpp.retrieveByOrigin(UAA, zone.getId()));
    assertEquals(UAA, idpp.retrieveByOrigin(UAA, zone.getId()).getOriginKey());
    // create login-server provider
    IdentityProvider provider = new IdentityProvider().setOriginKey(LOGIN_SERVER).setActive(true).setIdentityZoneId(zone.getId()).setName("Delete Test").setType(LOGIN_SERVER);
    IdentityZoneHolder.set(zone);
    provider = idpp.create(provider, provider.getIdentityZoneId());
    assertNotNull(idpp.retrieveByOrigin(LOGIN_SERVER, zone.getId()));
    assertEquals(provider.getId(), idpp.retrieveByOrigin(LOGIN_SERVER, zone.getId()).getId());
    // create user and add user to group
    ScimUser user = getScimUser();
    user.setOrigin(LOGIN_SERVER);
    user = userProvisioning.createUser(user, "", IdentityZoneHolder.get().getId());
    assertNotNull(userProvisioning.retrieve(user.getId(), IdentityZoneHolder.get().getId()));
    assertEquals(zone.getId(), user.getZoneId());
    // create group
    ScimGroup group = new ScimGroup("Delete Test Group");
    group.setZoneId(zone.getId());
    group = groupProvisioning.create(group, IdentityZoneHolder.get().getId());
    membershipManager.addMember(group.getId(), new ScimGroupMember(user.getId(), ScimGroupMember.Type.USER), IdentityZoneHolder.get().getId());
    assertEquals(zone.getId(), group.getZoneId());
    assertNotNull(groupProvisioning.retrieve(group.getId(), IdentityZoneHolder.get().getId()));
    assertEquals("Delete Test Group", groupProvisioning.retrieve(group.getId(), IdentityZoneHolder.get().getId()).getDisplayName());
    assertEquals(1, membershipManager.getMembers(group.getId(), false, IdentityZoneHolder.get().getId()).size());
    // failed authenticated user
    mockMvc.perform(post("/login.do").header("Host", zone.getSubdomain() + ".localhost").with(cookieCsrf()).accept(TEXT_HTML_VALUE).param("username", user.getUserName()).param("password", "adasda")).andExpect(status().isFound());
    // ensure we have some audit records
    // this doesn't work yet
    // assertThat(template.queryForObject("select count(*) from sec_audit where identity_zone_id=?", new Object[] {user.getZoneId()}, Integer.class), greaterThan(0));
    // create an external group map
    IdentityZoneHolder.set(zone);
    externalMembershipManager.mapExternalGroup(group.getId(), "externalDeleteGroup", LOGIN_SERVER, IdentityZoneHolder.get().getId());
    assertEquals(1, externalMembershipManager.getExternalGroupMapsByGroupId(group.getId(), LOGIN_SERVER, IdentityZoneHolder.get().getId()).size());
    assertThat(template.queryForObject("select count(*) from external_group_mapping where origin=?", new Object[] { LOGIN_SERVER }, Integer.class), is(1));
    // add user approvals
    approvalStore.addApproval(new Approval().setClientId(client.getClientId()).setScope("openid").setStatus(Approval.ApprovalStatus.APPROVED).setUserId(user.getId()), IdentityZoneHolder.get().getId());
    assertEquals(1, approvalStore.getApprovals(user.getId(), client.getClientId(), IdentityZoneHolder.get().getId()).size());
    // perform zone delete
    mockMvc.perform(delete("/identity-zones/{id}", zone.getId()).header("Authorization", "Bearer " + identityClientToken).accept(APPLICATION_JSON)).andExpect(status().isOk());
    mockMvc.perform(delete("/identity-zones/{id}", zone.getId()).header("Authorization", "Bearer " + identityClientToken).accept(APPLICATION_JSON)).andExpect(status().isNotFound());
    assertThat(template.queryForObject("select count(*) from identity_zone where id=?", new Object[] { zone.getId() }, Integer.class), is(0));
    assertThat(template.queryForObject("select count(*) from oauth_client_details where identity_zone_id=?", new Object[] { zone.getId() }, Integer.class), is(0));
    assertThat(template.queryForObject("select count(*) from groups where identity_zone_id=?", new Object[] { zone.getId() }, Integer.class), is(0));
    assertThat(template.queryForObject("select count(*) from sec_audit where identity_zone_id=?", new Object[] { zone.getId() }, Integer.class), is(0));
    assertThat(template.queryForObject("select count(*) from users where identity_zone_id=?", new Object[] { zone.getId() }, Integer.class), is(0));
    assertThat(template.queryForObject("select count(*) from external_group_mapping where origin=?", new Object[] { LOGIN_SERVER }, Integer.class), is(0));
    try {
        externalMembershipManager.getExternalGroupMapsByGroupId(group.getId(), LOGIN_SERVER, IdentityZoneHolder.get().getId());
        fail("no external groups should be found");
    } catch (ScimResourceNotFoundException ignored) {
    }
    assertThat(template.queryForObject("select count(*) from authz_approvals where user_id=?", new Object[] { user.getId() }, Integer.class), is(0));
    assertEquals(0, approvalStore.getApprovals(user.getId(), client.getClientId(), IdentityZoneHolder.get().getId()).size());
}
Also used : BaseClientDetails(org.springframework.security.oauth2.provider.client.BaseClientDetails) IdentityProviderProvisioning(org.cloudfoundry.identity.uaa.provider.IdentityProviderProvisioning) JdbcIdentityProviderProvisioning(org.cloudfoundry.identity.uaa.provider.JdbcIdentityProviderProvisioning) IdentityProvider(org.cloudfoundry.identity.uaa.provider.IdentityProvider) ScimResourceNotFoundException(org.cloudfoundry.identity.uaa.scim.exception.ScimResourceNotFoundException) Matchers.containsString(org.hamcrest.Matchers.containsString) JdbcScimGroupProvisioning(org.cloudfoundry.identity.uaa.scim.jdbc.JdbcScimGroupProvisioning) JdbcTemplate(org.springframework.jdbc.core.JdbcTemplate) MvcResult(org.springframework.test.web.servlet.MvcResult) ApprovalStore(org.cloudfoundry.identity.uaa.approval.ApprovalStore) Approval(org.cloudfoundry.identity.uaa.approval.Approval) KeyWithCertTest(org.cloudfoundry.identity.uaa.util.KeyWithCertTest) Test(org.junit.jupiter.api.Test) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 24 with Approval

use of org.cloudfoundry.identity.uaa.approval.Approval in project uaa by cloudfoundry.

the class DeprecatedUaaTokenServicesTests method testCreateAccessTokenAuthcodeGrantNarrowerScopes.

@Test
public void testCreateAccessTokenAuthcodeGrantNarrowerScopes() {
    Calendar expiresAt = Calendar.getInstance();
    expiresAt.add(Calendar.MILLISECOND, 3000);
    Calendar updatedAt = Calendar.getInstance();
    updatedAt.add(Calendar.MILLISECOND, -1000);
    tokenSupport.approvalStore.addApproval(new Approval().setUserId(tokenSupport.userId).setClientId(CLIENT_ID).setScope(tokenSupport.readScope.get(0)).setExpiresAt(expiresAt.getTime()).setStatus(ApprovalStatus.APPROVED).setLastUpdatedAt(updatedAt.getTime()), IdentityZoneHolder.get().getId());
    tokenSupport.approvalStore.addApproval(new Approval().setUserId(tokenSupport.userId).setClientId(CLIENT_ID).setScope(tokenSupport.writeScope.get(0)).setExpiresAt(expiresAt.getTime()).setStatus(ApprovalStatus.APPROVED).setLastUpdatedAt(updatedAt.getTime()), IdentityZoneHolder.get().getId());
    // First Request
    AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, tokenSupport.requestedAuthScopes);
    authorizationRequest.setResourceIds(new HashSet<>(tokenSupport.resourceIds));
    Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters());
    azParameters.put(GRANT_TYPE, GRANT_TYPE_AUTHORIZATION_CODE);
    authorizationRequest.setRequestParameters(azParameters);
    Authentication userAuthentication = tokenSupport.defaultUserAuthentication;
    OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(), userAuthentication);
    OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication);
    assertThat(accessToken, scope(is(tokenSupport.requestedAuthScopes)));
    OAuth2RefreshToken refreshToken = accessToken.getRefreshToken();
    assertThat(refreshToken, is(not(nullValue())));
    assertThat(refreshToken, OAuth2RefreshTokenMatchers.scope(is(tokenSupport.requestedAuthScopes)));
    assertThat(refreshToken, OAuth2RefreshTokenMatchers.audience(is(tokenSupport.resourceIds)));
    // Second request with reduced scopes
    AuthorizationRequest reducedScopeAuthorizationRequest = new AuthorizationRequest(CLIENT_ID, tokenSupport.readScope);
    reducedScopeAuthorizationRequest.setResourceIds(new HashSet<>(tokenSupport.resourceIds));
    Map<String, String> refreshAzParameters = new HashMap<>(reducedScopeAuthorizationRequest.getRequestParameters());
    refreshAzParameters.put(GRANT_TYPE, GRANT_TYPE_REFRESH_TOKEN);
    reducedScopeAuthorizationRequest.setRequestParameters(refreshAzParameters);
    OAuth2Authentication reducedScopeAuthentication = new OAuth2Authentication(reducedScopeAuthorizationRequest.createOAuth2Request(), userAuthentication);
    OAuth2AccessToken reducedScopeAccessToken = tokenServices.refreshAccessToken(accessToken.getRefreshToken().getValue(), tokenSupport.requestFactory.createTokenRequest(reducedScopeAuthorizationRequest, "refresh_token"));
    // AT should have the new scopes, RT should be the same
    assertThat(reducedScopeAccessToken, scope(is(tokenSupport.readScope)));
    assertEquals(reducedScopeAccessToken.getRefreshToken(), accessToken.getRefreshToken());
}
Also used : AuthorizationRequest(org.springframework.security.oauth2.provider.AuthorizationRequest) OAuth2RefreshToken(org.springframework.security.oauth2.common.OAuth2RefreshToken) CompositeExpiringOAuth2RefreshToken(org.cloudfoundry.identity.uaa.oauth.refresh.CompositeExpiringOAuth2RefreshToken) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) Authentication(org.springframework.security.core.Authentication) DefaultOAuth2AccessToken(org.springframework.security.oauth2.common.DefaultOAuth2AccessToken) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) IsEmptyString.isEmptyString(org.hamcrest.text.IsEmptyString.isEmptyString) Approval(org.cloudfoundry.identity.uaa.approval.Approval)

Example 25 with Approval

use of org.cloudfoundry.identity.uaa.approval.Approval in project uaa by cloudfoundry.

the class DeprecatedUaaTokenServicesTests method readAccessToken.

private void readAccessToken(Set<String> excludedClaims) {
    tokenServices.setExcludedClaims(excludedClaims);
    AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, tokenSupport.requestedAuthScopes);
    authorizationRequest.setResourceIds(new HashSet<>(tokenSupport.resourceIds));
    Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters());
    azParameters.put(GRANT_TYPE, GRANT_TYPE_AUTHORIZATION_CODE);
    authorizationRequest.setRequestParameters(azParameters);
    Authentication userAuthentication = tokenSupport.defaultUserAuthentication;
    Calendar expiresAt = Calendar.getInstance();
    expiresAt.add(Calendar.MILLISECOND, 3000);
    Calendar updatedAt = Calendar.getInstance();
    updatedAt.add(Calendar.MILLISECOND, -1000);
    tokenSupport.approvalStore.addApproval(new Approval().setUserId(tokenSupport.userId).setClientId(CLIENT_ID).setScope(tokenSupport.readScope.get(0)).setExpiresAt(expiresAt.getTime()).setStatus(ApprovalStatus.APPROVED).setLastUpdatedAt(updatedAt.getTime()), IdentityZoneHolder.get().getId());
    tokenSupport.approvalStore.addApproval(new Approval().setUserId(tokenSupport.userId).setClientId(CLIENT_ID).setScope(tokenSupport.writeScope.get(0)).setExpiresAt(expiresAt.getTime()).setStatus(ApprovalStatus.APPROVED).setLastUpdatedAt(updatedAt.getTime()), IdentityZoneHolder.get().getId());
    Approval approval = new Approval().setUserId(tokenSupport.userId).setClientId(CLIENT_ID).setScope(OPENID).setExpiresAt(expiresAt.getTime()).setStatus(ApprovalStatus.APPROVED).setLastUpdatedAt(updatedAt.getTime());
    tokenSupport.approvalStore.addApproval(approval, IdentityZoneHolder.get().getId());
    OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(), userAuthentication);
    OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication);
    assertEquals(accessToken, tokenServices.readAccessToken(accessToken.getValue()));
    tokenSupport.approvalStore.revokeApproval(approval, IdentityZoneHolder.get().getId());
    try {
        tokenServices.readAccessToken(accessToken.getValue());
        fail("Approval has been revoked");
    } catch (InvalidTokenException x) {
        assertThat("Exception should be about approvals", x.getMessage().contains("some requested scopes are not approved"));
    }
}
Also used : InvalidTokenException(org.springframework.security.oauth2.common.exceptions.InvalidTokenException) AuthorizationRequest(org.springframework.security.oauth2.provider.AuthorizationRequest) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) Authentication(org.springframework.security.core.Authentication) DefaultOAuth2AccessToken(org.springframework.security.oauth2.common.DefaultOAuth2AccessToken) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) IsEmptyString.isEmptyString(org.hamcrest.text.IsEmptyString.isEmptyString) Approval(org.cloudfoundry.identity.uaa.approval.Approval)

Aggregations

Approval (org.cloudfoundry.identity.uaa.approval.Approval)80 Test (org.junit.jupiter.api.Test)34 AuthorizationRequest (org.springframework.security.oauth2.provider.AuthorizationRequest)29 Date (java.util.Date)26 OAuth2AccessToken (org.springframework.security.oauth2.common.OAuth2AccessToken)21 DefaultOAuth2AccessToken (org.springframework.security.oauth2.common.DefaultOAuth2AccessToken)19 BaseClientDetails (org.springframework.security.oauth2.provider.client.BaseClientDetails)18 Authentication (org.springframework.security.core.Authentication)17 OAuth2Authentication (org.springframework.security.oauth2.provider.OAuth2Authentication)17 IsEmptyString.isEmptyString (org.hamcrest.text.IsEmptyString.isEmptyString)16 Test (org.junit.Test)16 ApprovalStore (org.cloudfoundry.identity.uaa.approval.ApprovalStore)7 MockHttpServletRequestBuilder (org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder)6 ClientDetailsModification (org.cloudfoundry.identity.uaa.oauth.client.ClientDetailsModification)5 ScimUser (org.cloudfoundry.identity.uaa.scim.ScimUser)5 ClientDetails (org.springframework.security.oauth2.provider.ClientDetails)5 ArrayList (java.util.ArrayList)4 ClientDetailsHelper.arrayFromString (org.cloudfoundry.identity.uaa.mock.util.ClientDetailsHelper.arrayFromString)4 ClientDetailsHelper.clientArrayFromString (org.cloudfoundry.identity.uaa.mock.util.ClientDetailsHelper.clientArrayFromString)4 ClientDetailsHelper.clientFromString (org.cloudfoundry.identity.uaa.mock.util.ClientDetailsHelper.clientFromString)4