diff options
Diffstat (limited to 'src/test/java/com/juick/server')
-rw-r--r-- | src/test/java/com/juick/server/tests/ServerTests.java | 186 |
1 files changed, 9 insertions, 177 deletions
diff --git a/src/test/java/com/juick/server/tests/ServerTests.java b/src/test/java/com/juick/server/tests/ServerTests.java index f01f58a7..5d149277 100644 --- a/src/test/java/com/juick/server/tests/ServerTests.java +++ b/src/test/java/com/juick/server/tests/ServerTests.java @@ -32,11 +32,9 @@ import com.jayway.jsonpath.JsonPath; import com.juick.*; import com.juick.model.Tag; import com.juick.model.*; -import com.juick.server.MockDeleteListener; import com.juick.server.MockNotificationListener; import com.juick.server.MockUpdateListener; import com.juick.service.*; -import com.juick.service.activities.DeleteUserEvent; import com.juick.service.activities.UpdateEvent; import com.juick.service.component.SystemEvent; import com.juick.test.util.MockUtils; @@ -67,6 +65,7 @@ import jakarta.xml.bind.JAXBContext; import jakarta.xml.bind.JAXBException; import jakarta.xml.bind.Marshaller; import jakarta.xml.bind.Unmarshaller; +import okhttp3.OkHttpClient; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.IteratorUtils; import org.apache.commons.io.IOUtils; @@ -88,12 +87,10 @@ import org.springframework.core.convert.ConversionService; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.http.*; -import org.springframework.http.client.ClientHttpRequestFactory; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.mock.web.MockHttpSession; import org.springframework.mock.web.MockMultipartFile; import org.springframework.test.context.TestPropertySource; -import org.springframework.test.web.client.MockRestServiceServer; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; @@ -103,11 +100,8 @@ import org.springframework.util.DigestUtils; import org.springframework.util.FileSystemUtils; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; -import org.springframework.web.client.ResourceAccessException; -import org.springframework.web.client.RestTemplate; import org.springframework.web.util.UriComponents; import org.springframework.web.util.UriComponentsBuilder; -import org.tomitribe.auth.signatures.Base64; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; @@ -127,7 +121,6 @@ import java.io.*; import java.net.URI; import java.nio.charset.StandardCharsets; import java.nio.file.*; -import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.spec.InvalidKeySpecException; @@ -142,7 +135,6 @@ import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.StreamSupport; -import static com.juick.www.api.activity.model.Context.ACTIVITY_MEDIA_TYPE; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import static org.hamcrest.collection.IsEmptyCollection.empty; @@ -150,10 +142,6 @@ import static org.junit.jupiter.api.Assertions.*; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.httpBasic; import static org.springframework.test.util.AssertionErrors.assertNotEquals; -import static org.springframework.test.web.client.ExpectedCount.times; -import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; -import static org.springframework.test.web.client.response.MockRestResponseCreators.withStatus; -import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; @@ -161,6 +149,8 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. /** * Created by vitalyster on 25.11.2016. */ + +// TODO: test deleted when GONE, test deleted when suspended, test incorrect certificates @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) @TestPropertySource(properties = {"ios_app_id=12345678.com.juick.ExampleApp"}) @AutoConfigureMockMvc @@ -219,7 +209,7 @@ public class ServerTests { @Value("${web_domain:localhost}") private String webDomain; @Inject - private RestTemplate apClient; + private OkHttpClient apClient; @Value("classpath:snapshots/activity/testuser.json") private Resource testuserResponse; @@ -2056,9 +2046,9 @@ public class ServerTests { (Actor) activityPubService.get(URI.create("http://localhost:8080/u/freefd")).get(), (Actor) activityPubService.get(URI.create("http://localhost:8080/u/ugnich")).get(), create); - Message replyToExt = commandsManager - .processCommand(ugnich, String.format("#%d/1 PSSH YOBA ETO TI", msg.getMid()), emptyUri) - .getNewMessage() + var reply = commandsManager + .processCommand(ugnich, String.format("#%d/1 PSSH YOBA ETO TI", msg.getMid()), emptyUri); + var replyToExt = reply.getNewMessage() .get(); json = jsonMapper.writeValueAsString(Context.build( activityPubManager.makeNote( @@ -2076,98 +2066,13 @@ public class ServerTests { follow.setActor("http://localhost:8080/u/freefd"); follow.setObject(new Context("http://localhost:8080/u/ugnich")); var result = activityPubService.post(from, to, follow); - assertThat(result, is(HttpStatusCode.valueOf(202))); + assertThat(result, is(202)); String testuserResponseString = IOUtils.toString(testuserResponse.getInputStream(), StandardCharsets.UTF_8); Actor maliciousActor = jsonMapper.readValue(testuserResponseString, Actor.class); follow.setActor(maliciousActor.getId()); result = activityPubService.post(maliciousActor, to, follow); - assertThat(result, is(HttpStatusCode.valueOf(401))); - } - - @Test - @Order(1) - public void serviceSignatureAuth() throws Exception { - String meUri = "/api/me"; - Instant now = Instant.now(); - String requestDate = DateFormattersHolder.getHttpDateFormatter().format(now); - mockMvc.perform(get("/api/me").header("Date", requestDate)).andExpect(status().isUnauthorized()); - String testHost = "localhost:8080"; - Actor ugnichPerson = conversionService.convert(ugnich, Actor.class); - now = Instant.now(); - requestDate = DateFormattersHolder.getHttpDateFormatter().format(now); - String signatureString = signatureService.addSignature(ugnichPerson, testHost, "GET", meUri, - requestDate, - StringUtils.EMPTY); - MvcResult me = mockMvc.perform(get("/api/me") - .header("Host", testHost).header("Date", requestDate) - .header( "Signature", signatureString)).andExpect(status().isOk()).andReturn(); - User meUser = jsonMapper.readValue(me.getResponse().getContentAsString(), User.class); - assertThat(meUser, is(ugnich)); - String testuserResponseString = IOUtils.toString(testuserResponse.getInputStream(), - StandardCharsets.UTF_8); - ClientHttpRequestFactory originalRequestFactory = apClient.getRequestFactory(); - URI testuserUri = URI.create("https://example.com/u/testuser"); - URI testuserkeyUri = URI.create("https://example.com/u/testuser#main-key"); - URI testAppUri = URI.create("https://example.com/actor"); - URI testAppkeyUri = URI.create("https://example.com/actor#main-key"); - MockRestServiceServer restServiceServer = MockRestServiceServer.createServer(apClient); - restServiceServer.expect(times(4), requestTo(testuserUri)) - .andRespond(withSuccess(testuserResponseString, MediaType.APPLICATION_JSON)); - restServiceServer.expect(times(4), requestTo(testuserkeyUri)) - .andRespond(withSuccess(testuserResponseString, MediaType.APPLICATION_JSON)); - Person testuser = (Person) activityPubService.get(testuserUri).get(); - assertThat(testuser.getPublicKey().getPublicKeyPem(), is(testKeystoreManager.getPublicKeyPem())); - Instant now2 = Instant.now(); - String testRequestDate = DateFormattersHolder.getHttpDateFormatter().format(now2); - String inboxUri = "/api/inbox"; - var payload = IOUtils.toByteArray(testfollowRequest.getInputStream()); - byte[] digest = MessageDigest.getInstance("SHA-256").digest(payload); // (1) - String digestHeader = "SHA-256=" + new String(Base64.encodeBase64(digest)); - String testSignatureString = signatureService.addSignature(testuser, testHost, "POST", inboxUri, - testRequestDate, digestHeader, testKeystoreManager); - mockMvc.perform(post(inboxUri).header("Host", testHost).header("Date", testRequestDate) - .header("Digest", digestHeader).header("Signature", testSignatureString) - .contentType(Context.LD_JSON_MEDIA_TYPE).content(payload)) - .andExpect(status().isAccepted()); - mockMvc.perform(post(inboxUri).header("Host", "wronghost").header("Date", testRequestDate) - .header("Signature", testSignatureString).contentType(Context.LD_JSON_MEDIA_TYPE) - .content(IOUtils.toByteArray(testfollowRequest.getInputStream()))) - .andExpect(status().isUnauthorized()); - // digest required but not present - mockMvc.perform(post(inboxUri).header("Host", testHost).header("Date", testRequestDate) - .header("Signature", testSignatureString).contentType(Context.LD_JSON_MEDIA_TYPE) - .content(payload)) - .andExpect(status().isUnauthorized()); - apClient.setRequestFactory(originalRequestFactory); - } - - @Test - public void testFlaggingAsApplication() throws Exception { - var payload = IOUtils.toByteArray(flagPayload.getInputStream()); - var digest = MessageDigest.getInstance("SHA-256").digest(payload); // (1) - var digestHeader = "SHA-256=" + new String(Base64.encodeBase64(digest)); - var now2 = Instant.now(); - String inboxUri = "/api/inbox"; - String testHost = "localhost:8080"; - URI testAppUri = URI.create("https://example.com/actor"); - String testappResponseString = IOUtils.toString(testappResponse.getInputStream(), - StandardCharsets.UTF_8); - var testRequestDate = DateFormattersHolder.getHttpDateFormatter().format(now2); - ClientHttpRequestFactory originalRequestFactory = apClient.getRequestFactory(); - MockRestServiceServer restServiceServer = MockRestServiceServer.createServer(apClient); - restServiceServer.expect(times(2), requestTo(testAppUri)) - .andRespond(withSuccess(testappResponseString, MediaType.APPLICATION_JSON)); - Application testapp = (Application) activityPubService.get(testAppUri).get(); - assertThat(testapp.getPublicKey().getPublicKeyPem(), is(testKeystoreManager.getPublicKeyPem())); - var testSignatureString = signatureService.addSignature(testapp, testHost, "POST", inboxUri, - testRequestDate, - digestHeader, testKeystoreManager); - mockMvc.perform(post(inboxUri).header("Host", testHost).header("Date", testRequestDate) - .header("Signature", testSignatureString).header("Digest", digestHeader) - .contentType(Context.LD_JSON_MEDIA_TYPE).content(payload)) - .andExpect(status().isAccepted()); - apClient.setRequestFactory(originalRequestFactory); + assertThat(result, is(401)); } @Test @@ -2354,79 +2259,6 @@ public class ServerTests { } @Test - public void federatedUserDeletionFlowWhenItIsGone() throws Exception { - String deleteJsonStr = IOUtils.toString(new ClassPathResource("delete_user.json").getURI(), - StandardCharsets.UTF_8); - Delete delete = jsonMapper.readValue(deleteJsonStr, Delete.class); - ClientHttpRequestFactory originalRequestFactory = apClient.getRequestFactory(); - MockRestServiceServer restServiceServer = MockRestServiceServer.createServer(apClient); - restServiceServer.expect(times(2), requestTo(delete.getObject().getId())) - .andRespond(withStatus(HttpStatus.GONE)); - restServiceServer.expect(requestTo(delete.getObject().getId())).andRespond(response -> { - throw new ResourceAccessException("Connection reset"); - }); - mockMvc.perform(post("/api/inbox").contentType(ACTIVITY_MEDIA_TYPE).content(deleteJsonStr)) - .andExpect(status().isAccepted()); - mockMvc.perform(post("/api/inbox").contentType(ACTIVITY_MEDIA_TYPE).content(deleteJsonStr).header( - "Signature", - "keyId=\"https://example.com/users/deleted#main-key\",algorithm=\"rsa-sha256\",headers=\"(request-target) host date digest content-type\",signature=\"wHoU91JJBsIYcR1W1/57B0oG98t5Aa/TvGPw1B8KQlAp5KhpePnOzD1MZRgivBx7YKO6eYwDx+AX9dn6tjlAvzRLygv21H6UoDZFihWzeE1HM8pY2Pe4EhUgYBN0YuiKUi7W4TS9bDRAJ5vGNPUWATe+2o5Jcbux5cZYXFKKYbLBLD+/IlqPdHA2IXLZ52HFVVfBkPH5sSklV6XJtD/PHLK9R/I9w/mUpj9moUPQu44rR7KvxiGNuHla3vfDtJbkBqLMdScX91EG8373AulXPUiCCF7R2lJB0fFQedm2nSbcwBoJ32GEyOyOPFgPKG5zd9Fd5TfB1pmA8ZIE0sChfA==\"")) - .andExpect(status().isAccepted()); - apClient.setRequestFactory(originalRequestFactory); - } - - @MockBean - private MockDeleteListener deleteListener; - @Captor - protected ArgumentCaptor<DeleteUserEvent> deleteEventCaptor; - - @Test - public void federatedUserDeletionFlowWhenItIsSuspended() throws Exception { - String deleteJsonStr = IOUtils.toString(testDeleteRequest.getInputStream(), StandardCharsets.UTF_8); - Delete delete = jsonMapper.readValue(deleteJsonStr, Delete.class); - ClientHttpRequestFactory originalRequestFactory = apClient.getRequestFactory(); - MockRestServiceServer restServiceServer = MockRestServiceServer.createServer(apClient); - restServiceServer.expect(times(2), requestTo(delete.getObject().getId())) - .andRespond(withSuccess( - IOUtils.toString(testSuspendedUserResponse.getInputStream(), - StandardCharsets.UTF_8), - MediaType.APPLICATION_JSON)); - Person testuser = (Person) activityPubService.get(URI.create(delete.getObject().getId())).get(); - Instant now = Instant.now(); - String testRequestDate = DateFormattersHolder.getHttpDateFormatter().format(now); - String inboxUri = "/api/inbox"; - byte[] digest = MessageDigest.getInstance("SHA-256").digest(deleteJsonStr.getBytes()); - String digestHeader = "SHA-256=" + new String(Base64.encodeBase64(digest)); - String testSignatureString = signatureService.addSignature(testuser, "localhost", "POST", inboxUri, - testRequestDate, digestHeader, testKeystoreManager); - mockMvc.perform(post(inboxUri).contentType(ACTIVITY_MEDIA_TYPE).content(deleteJsonStr) - .header("Host", "localhost").header("Date", testRequestDate) - .header("Digest", digestHeader) - .header("Signature", testSignatureString)).andExpect(status().isAccepted()); - apClient.setRequestFactory(originalRequestFactory); - Mockito.verify(deleteListener, Mockito.times(1)).onApplicationEvent(deleteEventCaptor.capture()); - DeleteUserEvent receivedEvent = deleteEventCaptor.getValue(); - assertThat(receivedEvent.getUserUri(), is(testuser.getId())); - } - - @Test - @Order(2) - public void handleIncorrectCertificates() throws Exception { - String deleteJsonStr = IOUtils.toString(new ClassPathResource("delete_user.json").getURI(), - StandardCharsets.UTF_8); - Delete delete = jsonMapper.readValue(deleteJsonStr, Delete.class); - ClientHttpRequestFactory originalRequestFactory = apClient.getRequestFactory(); - MockRestServiceServer restServiceServer = MockRestServiceServer.createServer(apClient); - restServiceServer.expect(requestTo(delete.getObject().getId())).andRespond(response -> { - throw new ResourceAccessException("Connection reset"); - }); - mockMvc.perform(post("/api/inbox").contentType(ACTIVITY_MEDIA_TYPE).content(deleteJsonStr).header( - "Signature", - "keyId=\"https://example.com/users/deleted#main-key\",algorithm=\"rsa-sha256\",headers=\"(request-target) host date digest content-type\",signature=\"wHoU91JJBsIYcR1W1/57B0oG98t5Aa/TvGPw1B8KQlAp5KhpePnOzD1MZRgivBx7YKO6eYwDx+AX9dn6tjlAvzRLygv21H6UoDZFihWzeE1HM8pY2Pe4EhUgYBN0YuiKUi7W4TS9bDRAJ5vGNPUWATe+2o5Jcbux5cZYXFKKYbLBLD+/IlqPdHA2IXLZ52HFVVfBkPH5sSklV6XJtD/PHLK9R/I9w/mUpj9moUPQu44rR7KvxiGNuHla3vfDtJbkBqLMdScX91EG8373AulXPUiCCF7R2lJB0fFQedm2nSbcwBoJ32GEyOyOPFgPKG5zd9Fd5TfB1pmA8ZIE0sChfA==\"")) - .andExpect(status().isAccepted()); - apClient.setRequestFactory(originalRequestFactory); - } - - @Test public void legacyAvatarEndpoint() throws Exception { mockMvc.perform(get("/api/avatar").param("uname", "unknown")).andExpect(status().isOk()) .andExpect(content().bytes(IOUtils.toByteArray(defaultAvatar.getInputStream()))); |