Search in sources :

Example 1 with AbstractUaaEvent

use of org.cloudfoundry.identity.uaa.audit.event.AbstractUaaEvent in project uaa by cloudfoundry.

the class PasswordGrantAuthenticationManagerTest method testOIDCPasswordGrantInvalidLogin.

@Test
void testOIDCPasswordGrantInvalidLogin() {
    UaaLoginHint loginHint = mock(UaaLoginHint.class);
    when(loginHint.getOrigin()).thenReturn("oidcprovider");
    Authentication auth = mock(Authentication.class);
    when(auth.getPrincipal()).thenReturn("marissa");
    when(auth.getCredentials()).thenReturn("koala1");
    when(zoneAwareAuthzAuthenticationManager.extractLoginHint(auth)).thenReturn(loginHint);
    RestTemplate rt = mock(RestTemplate.class);
    when(restTemplateConfig.nonTrustingRestTemplate()).thenReturn(rt);
    ResponseEntity<Map<String, String>> response = mock(ResponseEntity.class);
    when(response.hasBody()).thenReturn(true);
    when(response.getBody()).thenReturn(Collections.singletonMap("id_token", "mytoken"));
    HttpClientErrorException exception = mock(HttpClientErrorException.class);
    when(rt.exchange(anyString(), any(HttpMethod.class), any(HttpEntity.class), any(ParameterizedTypeReference.class))).thenThrow(exception);
    try {
        instance.authenticate(auth);
        fail("No Exception thrown.");
    } catch (BadCredentialsException ignored) {
    }
    ArgumentCaptor<AbstractUaaEvent> eventArgumentCaptor = ArgumentCaptor.forClass(AbstractUaaEvent.class);
    verify(eventPublisher, times(1)).publishEvent(eventArgumentCaptor.capture());
    assertEquals(1, eventArgumentCaptor.getAllValues().size());
    assertTrue(eventArgumentCaptor.getValue() instanceof IdentityProviderAuthenticationFailureEvent);
}
Also used : HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) HttpEntity(org.springframework.http.HttpEntity) IdentityProviderAuthenticationFailureEvent(org.cloudfoundry.identity.uaa.authentication.event.IdentityProviderAuthenticationFailureEvent) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) UaaLoginHint(org.cloudfoundry.identity.uaa.authentication.UaaLoginHint) Authentication(org.springframework.security.core.Authentication) ParameterizedTypeReference(org.springframework.core.ParameterizedTypeReference) RestTemplate(org.springframework.web.client.RestTemplate) AbstractUaaEvent(org.cloudfoundry.identity.uaa.audit.event.AbstractUaaEvent) Map(java.util.Map) HashMap(java.util.HashMap) MultiValueMap(org.springframework.util.MultiValueMap) HttpMethod(org.springframework.http.HttpMethod) Test(org.junit.jupiter.api.Test)

Example 2 with AbstractUaaEvent

use of org.cloudfoundry.identity.uaa.audit.event.AbstractUaaEvent in project uaa by cloudfoundry.

the class AbstractLdapMockMvcTest method testLogin.

@Test
void testLogin() throws Exception {
    getMockMvc().perform(get("/login").header(HOST, host)).andExpect(status().isOk()).andExpect(view().name("login")).andExpect(model().attributeDoesNotExist("saml"));
    getMockMvc().perform(post("/login.do").accept(TEXT_HTML_VALUE).header(HOST, host).with(cookieCsrf()).param("username", "marissa").param("password", "koaladsada")).andExpect(status().isFound()).andExpect(unauthenticated()).andExpect(redirectedUrl("/login?error=login_failure"));
    ArgumentCaptor<AbstractUaaEvent> captor = ArgumentCaptor.forClass(AbstractUaaEvent.class);
    verify(listener, atLeast(5)).onApplicationEvent(captor.capture());
    List<AbstractUaaEvent> allValues = captor.getAllValues();
    assertThat(allValues.get(5), instanceOf(IdentityProviderAuthenticationFailureEvent.class));
    IdentityProviderAuthenticationFailureEvent event = (IdentityProviderAuthenticationFailureEvent) allValues.get(5);
    assertEquals("marissa", event.getUsername());
    assertEquals(OriginKeys.LDAP, event.getAuthenticationType());
    testLogger.reset();
    testSuccessfulLogin();
    assertThat(testLogger.getMessageCount(), is(5));
    String zoneId = zone.getZone().getIdentityZone().getId();
    ScimUser createdUser = jdbcScimUserProvisioning.retrieveAll(zoneId).stream().filter(dbUser -> dbUser.getUserName().equals("marissa2")).findFirst().get();
    String userCreatedLogMessage = testLogger.getFirstLogMessageOfType(AuditEventType.UserCreatedEvent);
    String expectedMessage = String.format("UserCreatedEvent ('[\"user_id=%s\",\"username=marissa2\"]'): principal=%s, origin=[caller=null], identityZoneId=[%s]", createdUser.getId(), createdUser.getId(), zoneId);
    assertThat(userCreatedLogMessage, is(expectedMessage));
    captor = ArgumentCaptor.forClass(AbstractUaaEvent.class);
    verify(listener, atLeast(5)).onApplicationEvent(captor.capture());
    allValues = captor.getAllValues();
    assertThat(allValues.get(13), instanceOf(IdentityProviderAuthenticationSuccessEvent.class));
    IdentityProviderAuthenticationSuccessEvent successEvent = (IdentityProviderAuthenticationSuccessEvent) allValues.get(13);
    assertEquals(OriginKeys.LDAP, successEvent.getAuthenticationType());
}
Also used : ScimUser(org.cloudfoundry.identity.uaa.scim.ScimUser) IdentityProviderAuthenticationSuccessEvent(org.cloudfoundry.identity.uaa.authentication.event.IdentityProviderAuthenticationSuccessEvent) IdentityProviderAuthenticationFailureEvent(org.cloudfoundry.identity.uaa.authentication.event.IdentityProviderAuthenticationFailureEvent) AbstractUaaEvent(org.cloudfoundry.identity.uaa.audit.event.AbstractUaaEvent) Test(org.junit.jupiter.api.Test)

Example 3 with AbstractUaaEvent

use of org.cloudfoundry.identity.uaa.audit.event.AbstractUaaEvent in project uaa by cloudfoundry.

the class ClientAdminEndpointsMockMvcTests method testCreateClientsTxSuccess.

@Test
void testCreateClientsTxSuccess() throws Exception {
    int count = 5;
    BaseClientDetails[] details = createBaseClients(count, SECRET, null);
    MockHttpServletRequestBuilder createClientPost = post("/oauth/clients/tx").header("Authorization", "Bearer " + adminToken).accept(APPLICATION_JSON).contentType(APPLICATION_JSON).content(JsonUtils.writeValueAsString(details));
    ResultActions result = mockMvc.perform(createClientPost);
    result.andExpect(status().isCreated());
    ClientDetails[] clients = clientArrayFromString(result.andReturn().getResponse().getContentAsString());
    for (ClientDetails client : clients) {
        ClientDetails c = getClient(client.getClientId());
        assertNotNull(c);
        assertNull(c.getClientSecret());
    }
    verify(mockApplicationEventPublisher, times(count)).publishEvent(abstractUaaEventCaptor.capture());
    for (AbstractUaaEvent event : abstractUaaEventCaptor.getAllValues()) {
        assertEquals(AuditEventType.ClientCreateSuccess, event.getAuditEvent().getType());
    }
}
Also used : BaseClientDetails(org.springframework.security.oauth2.provider.client.BaseClientDetails) ClientDetails(org.springframework.security.oauth2.provider.ClientDetails) BaseClientDetails(org.springframework.security.oauth2.provider.client.BaseClientDetails) MockHttpServletRequestBuilder(org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder) AbstractUaaEvent(org.cloudfoundry.identity.uaa.audit.event.AbstractUaaEvent) ResultActions(org.springframework.test.web.servlet.ResultActions) Test(org.junit.jupiter.api.Test)

Example 4 with AbstractUaaEvent

use of org.cloudfoundry.identity.uaa.audit.event.AbstractUaaEvent in project uaa by cloudfoundry.

the class ClientAdminEndpointsMockMvcTests method testAddUpdateDeleteClientsTxSuccess.

@Test
void testAddUpdateDeleteClientsTxSuccess() throws Exception {
    int count = 5;
    ClientDetailsModification[] details = new ClientDetailsModification[count * 3];
    for (int i = 0; i < count; i++) {
        details[i] = (ClientDetailsModification) createClient(adminToken, null, SECRET, null);
        details[i].setRefreshTokenValiditySeconds(120);
        details[i].setAction(ClientDetailsModification.UPDATE);
    }
    for (int i = count; i < (count * 2); i++) {
        details[i] = (ClientDetailsModification) createClient(adminToken, null, SECRET, null);
        details[i].setAction(ClientDetailsModification.DELETE);
    }
    for (int i = (count * 2); i < (count * 3); i++) {
        details[i] = createBaseClient(null, SECRET, null);
        details[i].setAction(ClientDetailsModification.ADD);
    }
    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().isOk());
    for (int i = 0; i < count; i++) {
        ClientDetails c = getClient(details[i].getClientId());
        assertNotNull(c);
        assertEquals(Integer.valueOf(120), c.getRefreshTokenValiditySeconds());
    }
    for (int i = count; i < (count * 2); i++) {
        ClientDetails c = getClient(details[i].getClientId());
        assertNull(c);
    }
    for (int i = (count * 2); i < (count * 3); i++) {
        ClientDetails c = getClient(details[i].getClientId());
        assertNotNull(c);
        assertNull(c.getRefreshTokenValiditySeconds());
    }
    verify(mockApplicationEventPublisher, times(count * 5)).publishEvent(abstractUaaEventCaptor.capture());
    int index = 0;
    for (AbstractUaaEvent event : abstractUaaEventCaptor.getAllValues()) {
        int swit = index / count;
        switch(swit) {
            case 0:
            case 1:
            case 4:
                {
                    // 1-10 and 21-25 events are create
                    assertEquals(AuditEventType.ClientCreateSuccess, event.getAuditEvent().getType());
                    assertEquals(ClientCreateEvent.class, event.getClass());
                    assertEquals(details[index < 10 ? index : (index - count * 2)].getClientId(), event.getAuditEvent().getPrincipalId());
                    break;
                }
            case 2:
                {
                    // the 11-15 events are update
                    assertEquals(AuditEventType.ClientUpdateSuccess, event.getAuditEvent().getType());
                    assertEquals(ClientUpdateEvent.class, event.getClass());
                    assertEquals(details[index - (count * 2)].getClientId(), event.getAuditEvent().getPrincipalId());
                    break;
                }
            case 3:
                {
                    // the 16-20 events are deletes
                    assertEquals(AuditEventType.ClientDeleteSuccess, event.getAuditEvent().getType());
                    assertEquals(ClientDeleteEvent.class, event.getClass());
                    assertEquals(details[index - count * 2].getClientId(), event.getAuditEvent().getPrincipalId());
                    break;
                }
        }
        index++;
    }
}
Also used : ClientUpdateEvent(org.cloudfoundry.identity.uaa.client.event.ClientUpdateEvent) ClientDetails(org.springframework.security.oauth2.provider.ClientDetails) BaseClientDetails(org.springframework.security.oauth2.provider.client.BaseClientDetails) MockHttpServletRequestBuilder(org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder) AbstractUaaEvent(org.cloudfoundry.identity.uaa.audit.event.AbstractUaaEvent) ClientCreateEvent(org.cloudfoundry.identity.uaa.client.event.ClientCreateEvent) ResultActions(org.springframework.test.web.servlet.ResultActions) ClientDeleteEvent(org.cloudfoundry.identity.uaa.client.event.ClientDeleteEvent) ClientDetailsModification(org.cloudfoundry.identity.uaa.oauth.client.ClientDetailsModification) Test(org.junit.jupiter.api.Test)

Example 5 with AbstractUaaEvent

use of org.cloudfoundry.identity.uaa.audit.event.AbstractUaaEvent in project uaa by cloudfoundry.

the class ClientAdminEndpointsMockMvcTests method testUpdateClientsTxSuccess.

@Test
void testUpdateClientsTxSuccess() throws Exception {
    int count = 5;
    BaseClientDetails[] details = new BaseClientDetails[count];
    for (int i = 0; i < details.length; i++) {
        details[i] = (BaseClientDetails) createClient(adminToken, null, SECRET, null);
        details[i].setRefreshTokenValiditySeconds(120);
    }
    MockHttpServletRequestBuilder updateClientPut = put("/oauth/clients/tx").header("Authorization", "Bearer " + adminToken).accept(APPLICATION_JSON).contentType(APPLICATION_JSON).content(JsonUtils.writeValueAsString(details));
    ResultActions result = mockMvc.perform(updateClientPut);
    result.andExpect(status().isOk());
    ClientDetails[] clients = clientArrayFromString(result.andReturn().getResponse().getContentAsString());
    for (ClientDetails client : clients) {
        assertNotNull(getClient(client.getClientId()));
        assertEquals(Integer.valueOf(120), client.getRefreshTokenValiditySeconds());
    }
    // create and then update events
    verify(mockApplicationEventPublisher, times(count * 2)).publishEvent(abstractUaaEventCaptor.capture());
    int index = 0;
    for (AbstractUaaEvent event : abstractUaaEventCaptor.getAllValues()) {
        if (index < count) {
            assertEquals(AuditEventType.ClientCreateSuccess, event.getAuditEvent().getType());
        } else {
            assertEquals(AuditEventType.ClientUpdateSuccess, event.getAuditEvent().getType());
        }
        index++;
    }
}
Also used : BaseClientDetails(org.springframework.security.oauth2.provider.client.BaseClientDetails) ClientDetails(org.springframework.security.oauth2.provider.ClientDetails) BaseClientDetails(org.springframework.security.oauth2.provider.client.BaseClientDetails) MockHttpServletRequestBuilder(org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder) AbstractUaaEvent(org.cloudfoundry.identity.uaa.audit.event.AbstractUaaEvent) ResultActions(org.springframework.test.web.servlet.ResultActions) Test(org.junit.jupiter.api.Test)

Aggregations

AbstractUaaEvent (org.cloudfoundry.identity.uaa.audit.event.AbstractUaaEvent)17 Test (org.junit.jupiter.api.Test)14 ResultActions (org.springframework.test.web.servlet.ResultActions)8 MockHttpServletRequestBuilder (org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder)8 ClientDetails (org.springframework.security.oauth2.provider.ClientDetails)6 BaseClientDetails (org.springframework.security.oauth2.provider.client.BaseClientDetails)6 MockHttpSession (org.springframework.mock.web.MockHttpSession)5 BeforeEach (org.junit.jupiter.api.BeforeEach)4 MfaAuthenticationSuccessEvent (org.cloudfoundry.identity.uaa.authentication.event.MfaAuthenticationSuccessEvent)3 CoreMatchers.containsString (org.hamcrest.CoreMatchers.containsString)3 RandomValueStringGenerator (org.springframework.security.oauth2.common.util.RandomValueStringGenerator)3 MockMvcResultHandlers.print (org.springframework.test.web.servlet.result.MockMvcResultHandlers.print)3 TypeReference (com.fasterxml.jackson.core.type.TypeReference)2 DefaultTestContext (org.cloudfoundry.identity.uaa.DefaultTestContext)2 Approval (org.cloudfoundry.identity.uaa.approval.Approval)2 AuditEventType (org.cloudfoundry.identity.uaa.audit.AuditEventType)2 IdentityProviderAuthenticationFailureEvent (org.cloudfoundry.identity.uaa.authentication.event.IdentityProviderAuthenticationFailureEvent)2 InterceptingLogger (org.cloudfoundry.identity.uaa.mock.util.InterceptingLogger)2 MockMvcUtils (org.cloudfoundry.identity.uaa.mock.util.MockMvcUtils)2 MockMvcUtils.httpBearer (org.cloudfoundry.identity.uaa.mock.util.MockMvcUtils.httpBearer)2