Search in sources :

Example 1 with SubscribeToTopicRequest

use of software.amazon.awssdk.aws.greengrass.model.SubscribeToTopicRequest in project aws-greengrass-nucleus by aws-greengrass.

the class IPCPubSubTest method GIVEN_pubsubclient_with_event_stream_WHEN_subscribe_authorization_changes_to_authorized_THEN_succeeds.

@SuppressWarnings({ "PMD.AvoidCatchingGenericException" })
@Test
void GIVEN_pubsubclient_with_event_stream_WHEN_subscribe_authorization_changes_to_authorized_THEN_succeeds() throws Exception {
    LogConfig.getRootLogConfig().setLevel(Level.DEBUG);
    String topicName = "topicName";
    SubscribeToTopicRequest subscribeToTopicRequest = new SubscribeToTopicRequest();
    subscribeToTopicRequest.setTopic(topicName);
    CountDownLatch subscriptionLatch = new CountDownLatch(1);
    Slf4jLogAdapter.addGlobalListener(m -> {
        if (m.getMessage().contains("Subscribed to topic")) {
            subscriptionLatch.countDown();
        }
    });
    String authToken = IPCTestUtils.getAuthTokeForService(kernel, "OnlyPublish");
    SocketOptions socketOptions = TestUtils.getSocketOptionsForIPC();
    try (EventStreamRPCConnection clientConnection = IPCTestUtils.connectToGGCOverEventStreamIPC(socketOptions, authToken, kernel)) {
        GreengrassCoreIPCClient greengrassCoreIPCClient = new GreengrassCoreIPCClient(clientConnection);
        assertTrue(kernel.getContext().get(AuthorizationModule.class).isPresent(TOKEN_EXCHANGE_SERVICE_TOPICS, TES_DEFAULT_POLICY));
        CompletableFuture<SubscribeToTopicResponse> fut = greengrassCoreIPCClient.subscribeToTopic(subscribeToTopicRequest, getOptionalStreamResponseHandler()).getResponse();
        ExecutionException executionException = assertThrows(ExecutionException.class, () -> fut.get(3, TimeUnit.SECONDS));
        assertTrue(executionException.getCause() instanceof UnauthorizedError);
        UnauthorizedError unauthorizedError = (UnauthorizedError) executionException.getCause();
        assertEquals("Principal OnlyPublish is not authorized to perform aws.greengrass.ipc.pubsub:aws.greengrass#SubscribeToTopic on resource topicName", unauthorizedError.getMessage());
    }
    Topics aclTopic = kernel.findServiceTopic("OnlyPublish").findTopics(CONFIGURATION_CONFIG_KEY, ACCESS_CONTROL_NAMESPACE_TOPIC);
    Map<String, Object> newAcl = OBJECT_MAPPER.readValue(newAclStr, new TypeReference<Map<String, Object>>() {
    });
    aclTopic.updateFromMap(newAcl, new UpdateBehaviorTree(UpdateBehaviorTree.UpdateBehavior.REPLACE, System.currentTimeMillis()));
    // Block until events are completed
    kernel.getContext().waitForPublishQueueToClear();
    assertTrue(kernel.getContext().get(AuthorizationModule.class).isPresent(TOKEN_EXCHANGE_SERVICE_TOPICS, TES_DEFAULT_POLICY));
    try (EventStreamRPCConnection clientConnection = IPCTestUtils.connectToGGCOverEventStreamIPC(socketOptions, authToken, kernel)) {
        GreengrassCoreIPCClient greengrassCoreIPCClient = new GreengrassCoreIPCClient(clientConnection);
        CompletableFuture<SubscribeToTopicResponse> fut = greengrassCoreIPCClient.subscribeToTopic(subscribeToTopicRequest, getOptionalStreamResponseHandler()).getResponse();
        try {
            fut.get(3, TimeUnit.SECONDS);
        } catch (Exception e) {
            logger.atError().setCause(e).log("Error when subscribing to component updates");
            fail("Caught exception when subscribing to component updates");
        }
        assertTrue(subscriptionLatch.await(10, TimeUnit.SECONDS));
    }
    aclTopic = kernel.findServiceTopic("OnlyPublish").findTopics(CONFIGURATION_CONFIG_KEY, ACCESS_CONTROL_NAMESPACE_TOPIC);
    Map<String, Object> oldAcl = OBJECT_MAPPER.readValue(oldAclStr, new TypeReference<Map<String, Object>>() {
    });
    aclTopic.updateFromMap(oldAcl, new UpdateBehaviorTree(UpdateBehaviorTree.UpdateBehavior.REPLACE, System.currentTimeMillis()));
    // Block until events are completed
    kernel.getContext().runOnPublishQueueAndWait(() -> {
    });
}
Also used : Topics(com.aws.greengrass.config.Topics) SocketOptions(software.amazon.awssdk.crt.io.SocketOptions) EventStreamRPCConnection(software.amazon.awssdk.eventstreamrpc.EventStreamRPCConnection) CountDownLatch(java.util.concurrent.CountDownLatch) UnauthorizedError(software.amazon.awssdk.aws.greengrass.model.UnauthorizedError) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) UpdateBehaviorTree(com.aws.greengrass.config.UpdateBehaviorTree) GreengrassCoreIPCClient(software.amazon.awssdk.aws.greengrass.GreengrassCoreIPCClient) ExecutionException(java.util.concurrent.ExecutionException) SubscribeToTopicResponse(software.amazon.awssdk.aws.greengrass.model.SubscribeToTopicResponse) Map(java.util.Map) SubscribeToTopicRequest(software.amazon.awssdk.aws.greengrass.model.SubscribeToTopicRequest) Test(org.junit.jupiter.api.Test)

Example 2 with SubscribeToTopicRequest

use of software.amazon.awssdk.aws.greengrass.model.SubscribeToTopicRequest in project aws-greengrass-nucleus by aws-greengrass.

the class IPCPubSubTest method GIVEN_PubSubEventStreamClient_WHEN_subscribe_wildcard_is_not_authorized_THEN_Fail.

@Test
void GIVEN_PubSubEventStreamClient_WHEN_subscribe_wildcard_is_not_authorized_THEN_Fail() throws Exception {
    String topicName = "topicName/#";
    SubscribeToTopicRequest subscribeToTopicRequest = new SubscribeToTopicRequest();
    subscribeToTopicRequest.setTopic(topicName);
    // Allowed resource /to*/#
    String authToken = IPCTestUtils.getAuthTokeForService(kernel, "SubscribeAndPublishWildcard");
    SocketOptions socketOptions = TestUtils.getSocketOptionsForIPC();
    try (EventStreamRPCConnection clientConnection = IPCTestUtils.connectToGGCOverEventStreamIPC(socketOptions, authToken, kernel)) {
        GreengrassCoreIPCClient greengrassCoreIPCClient = new GreengrassCoreIPCClient(clientConnection);
        ExecutionException executionException = assertThrows(ExecutionException.class, () -> greengrassCoreIPCClient.subscribeToTopic(subscribeToTopicRequest, getOptionalStreamResponseHandler()).getResponse().get());
        assertTrue(executionException.getCause() instanceof UnauthorizedError);
        UnauthorizedError unauthorizedError = (UnauthorizedError) executionException.getCause();
        assertEquals("Principal SubscribeAndPublishWildcard is not authorized to perform aws.greengrass.ipc" + ".pubsub:aws.greengrass#SubscribeToTopic on resource topicName/#", unauthorizedError.getMessage());
    }
}
Also used : SocketOptions(software.amazon.awssdk.crt.io.SocketOptions) GreengrassCoreIPCClient(software.amazon.awssdk.aws.greengrass.GreengrassCoreIPCClient) EventStreamRPCConnection(software.amazon.awssdk.eventstreamrpc.EventStreamRPCConnection) ExecutionException(java.util.concurrent.ExecutionException) UnauthorizedError(software.amazon.awssdk.aws.greengrass.model.UnauthorizedError) SubscribeToTopicRequest(software.amazon.awssdk.aws.greengrass.model.SubscribeToTopicRequest) Test(org.junit.jupiter.api.Test)

Example 3 with SubscribeToTopicRequest

use of software.amazon.awssdk.aws.greengrass.model.SubscribeToTopicRequest in project aws-greengrass-nucleus by aws-greengrass.

the class IPCPubSubTest method GIVEN_pubsubclient_with_event_stream_WHEN_subscribe_is_not_authorized_THEN_Fail.

@Test
void GIVEN_pubsubclient_with_event_stream_WHEN_subscribe_is_not_authorized_THEN_Fail() throws Exception {
    String topicName = "topicName";
    SubscribeToTopicRequest subscribeToTopicRequest = new SubscribeToTopicRequest();
    subscribeToTopicRequest.setTopic(topicName);
    String authToken = IPCTestUtils.getAuthTokeForService(kernel, "PublishNotSubscribe");
    SocketOptions socketOptions = TestUtils.getSocketOptionsForIPC();
    try (EventStreamRPCConnection clientConnection = IPCTestUtils.connectToGGCOverEventStreamIPC(socketOptions, authToken, kernel)) {
        GreengrassCoreIPCClient greengrassCoreIPCClient = new GreengrassCoreIPCClient(clientConnection);
        ExecutionException executionException = assertThrows(ExecutionException.class, () -> greengrassCoreIPCClient.subscribeToTopic(subscribeToTopicRequest, getOptionalStreamResponseHandler()).getResponse().get());
        assertTrue(executionException.getCause() instanceof UnauthorizedError);
        UnauthorizedError unauthorizedError = (UnauthorizedError) executionException.getCause();
        assertEquals("Principal PublishNotSubscribe is not authorized to perform aws.greengrass.ipc.pubsub:aws.greengrass#SubscribeToTopic on resource topicName", unauthorizedError.getMessage());
    }
}
Also used : SocketOptions(software.amazon.awssdk.crt.io.SocketOptions) GreengrassCoreIPCClient(software.amazon.awssdk.aws.greengrass.GreengrassCoreIPCClient) EventStreamRPCConnection(software.amazon.awssdk.eventstreamrpc.EventStreamRPCConnection) ExecutionException(java.util.concurrent.ExecutionException) UnauthorizedError(software.amazon.awssdk.aws.greengrass.model.UnauthorizedError) SubscribeToTopicRequest(software.amazon.awssdk.aws.greengrass.model.SubscribeToTopicRequest) Test(org.junit.jupiter.api.Test)

Example 4 with SubscribeToTopicRequest

use of software.amazon.awssdk.aws.greengrass.model.SubscribeToTopicRequest in project aws-greengrass-nucleus by aws-greengrass.

the class PubSubIPCEventStreamAgentTest method GIVEN_subscribe_topic_to_all_sources_WHEN_subscribe_THEN_added_all_services_listeners.

@Test
void GIVEN_subscribe_topic_to_all_sources_WHEN_subscribe_THEN_added_all_services_listeners() throws AuthorizationException {
    SubscribeToTopicRequest subscribeToTopicRequest = new SubscribeToTopicRequest();
    subscribeToTopicRequest.setTopic(TEST_TOPIC);
    try (PubSubIPCEventStreamAgent.SubscribeToTopicOperationHandler subscribeToTopicHandler = pubSubIPCEventStreamAgent.getSubscribeToTopicHandler(mockContext)) {
        SubscribeToTopicResponse subscribeToTopicResponse = subscribeToTopicHandler.handleRequest(subscribeToTopicRequest);
        assertNotNull(subscribeToTopicResponse);
        verify(authorizationHandler).isAuthorized(eq(PUB_SUB_SERVICE_NAME), permissionArgumentCaptor.capture(), eq(ResourceLookupPolicy.MQTT_STYLE));
        Permission capturedPermission = permissionArgumentCaptor.getValue();
        assertThat(capturedPermission.getOperation(), is(GreengrassCoreIPCService.SUBSCRIBE_TO_TOPIC));
        assertThat(capturedPermission.getPrincipal(), is(TEST_SERVICE));
        assertThat(capturedPermission.getResource(), is(TEST_TOPIC));
        assertTrue(pubSubIPCEventStreamAgent.getListeners().containsKey(TEST_TOPIC));
        assertEquals(1, pubSubIPCEventStreamAgent.getListeners().get(TEST_TOPIC).size());
    }
}
Also used : Permission(com.aws.greengrass.authorization.Permission) SubscribeToTopicResponse(software.amazon.awssdk.aws.greengrass.model.SubscribeToTopicResponse) SubscribeToTopicRequest(software.amazon.awssdk.aws.greengrass.model.SubscribeToTopicRequest) Test(org.junit.jupiter.api.Test)

Example 5 with SubscribeToTopicRequest

use of software.amazon.awssdk.aws.greengrass.model.SubscribeToTopicRequest in project aws-iot-device-sdk-java-v2 by aws.

the class GreengrassV2ClientTest method testV2Client.

@Test
public void testV2Client() throws InterruptedException, ExecutionException, TimeoutException {
    assertEquals(authenticationRequest.getAuthToken(), "myAuthToken");
    CreateLocalDeploymentResponse depResp = client.createLocalDeployment(new CreateLocalDeploymentRequest());
    assertEquals("deployment", depResp.getDeploymentId());
    CompletableFuture<CreateLocalDeploymentResponse> asyncDepResp = client.createLocalDeploymentAsync(new CreateLocalDeploymentRequest());
    assertEquals("deployment", asyncDepResp.get().getDeploymentId());
    CompletableFuture<String> receivedMessage = new CompletableFuture<>();
    CompletableFuture<String> finalReceivedMessage = receivedMessage;
    GreengrassCoreIPCClientV2.StreamingResponse<SubscribeToTopicResponse, SubscribeToTopicResponseHandler> subResp = client.subscribeToTopic(new SubscribeToTopicRequest().withTopic("abc"), (x) -> {
        if (!Thread.currentThread().getName().contains("pool")) {
            System.out.println(Thread.currentThread().getName());
            finalReceivedMessage.completeExceptionally(new RuntimeException("Ran on event loop instead of executor"));
        }
        finalReceivedMessage.complete(new String(x.getBinaryMessage().getMessage()));
    }, Optional.empty(), Optional.empty());
    assertEquals("message", receivedMessage.get());
    subResp.getHandler().closeStream().get();
    subscriptionClosed.get(1, TimeUnit.SECONDS);
    subscriptionClosed = new CompletableFuture<>();
    receivedMessage = new CompletableFuture<>();
    CompletableFuture<String> finalReceivedMessage1 = receivedMessage;
    subResp = client.subscribeToTopic(new SubscribeToTopicRequest().withTopic("abc"), new StreamResponseHandler<SubscriptionResponseMessage>() {

        @Override
        public void onStreamEvent(SubscriptionResponseMessage streamEvent) {
            if (!Thread.currentThread().getName().contains("pool")) {
                finalReceivedMessage1.completeExceptionally(new RuntimeException("Ran on event loop instead of executor"));
            }
            finalReceivedMessage1.complete(new String(streamEvent.getBinaryMessage().getMessage()));
        }

        @Override
        public boolean onStreamError(Throwable error) {
            return false;
        }

        @Override
        public void onStreamClosed() {
        }
    });
    assertEquals("message", receivedMessage.get());
    subResp.getHandler().closeStream().get();
    subscriptionClosed.get(1, TimeUnit.SECONDS);
    subscriptionClosed = new CompletableFuture<>();
    receivedMessage = new CompletableFuture<>();
    CompletableFuture<String> finalReceivedMessage2 = receivedMessage;
    GreengrassCoreIPCClientV2.StreamingResponse<CompletableFuture<SubscribeToTopicResponse>, SubscribeToTopicResponseHandler> subRespAsync = client.subscribeToTopicAsync(new SubscribeToTopicRequest().withTopic("abc"), new StreamResponseHandler<SubscriptionResponseMessage>() {

        @Override
        public void onStreamEvent(SubscriptionResponseMessage streamEvent) {
            if (!Thread.currentThread().getName().contains("pool")) {
                finalReceivedMessage2.completeExceptionally(new RuntimeException("Ran on event loop instead of executor"));
            }
            finalReceivedMessage2.complete(new String(streamEvent.getBinaryMessage().getMessage()));
        }

        @Override
        public boolean onStreamError(Throwable error) {
            return false;
        }

        @Override
        public void onStreamClosed() {
        }
    });
    assertEquals("message", receivedMessage.get());
    subRespAsync.getHandler().closeStream().get();
    subscriptionClosed.get(1, TimeUnit.SECONDS);
    subscriptionClosed = new CompletableFuture<>();
    receivedMessage = new CompletableFuture<>();
    CompletableFuture<String> finalReceivedMessage3 = receivedMessage;
    subRespAsync = client.subscribeToTopicAsync(new SubscribeToTopicRequest().withTopic("abc"), (x) -> {
        if (!Thread.currentThread().getName().contains("pool")) {
            finalReceivedMessage3.completeExceptionally(new RuntimeException("Ran on event loop instead of executor"));
        }
        finalReceivedMessage3.complete(new String(x.getBinaryMessage().getMessage()));
    }, Optional.empty(), Optional.empty());
    assertEquals("message", receivedMessage.get());
    subRespAsync.getHandler().closeStream().get();
    subscriptionClosed.get(1, TimeUnit.SECONDS);
}
Also used : BeforeEach(org.junit.jupiter.api.BeforeEach) GreengrassCoreIPCClientV2(software.amazon.awssdk.aws.greengrass.GreengrassCoreIPCClientV2) SocketOptions(software.amazon.awssdk.crt.io.SocketOptions) TimeoutException(java.util.concurrent.TimeoutException) BinaryMessage(software.amazon.awssdk.aws.greengrass.model.BinaryMessage) Random(java.util.Random) CompletableFuture(java.util.concurrent.CompletableFuture) GreengrassCoreIPCService(greengrass.GreengrassCoreIPCService) CrtResource(software.amazon.awssdk.crt.CrtResource) Gson(com.google.gson.Gson) GeneratedAbstractCreateLocalDeploymentOperationHandler(greengrass.GeneratedAbstractCreateLocalDeploymentOperationHandler) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) SubscribeToTopicResponseHandler(software.amazon.awssdk.aws.greengrass.SubscribeToTopicResponseHandler) Authorization(software.amazon.awssdk.eventstreamrpc.Authorization) StreamResponseHandler(software.amazon.awssdk.eventstreamrpc.StreamResponseHandler) RpcServer(software.amazon.awssdk.eventstreamrpc.RpcServer) IOException(java.io.IOException) EventStreamJsonMessage(software.amazon.awssdk.eventstreamrpc.model.EventStreamJsonMessage) EventLoopGroup(software.amazon.awssdk.crt.io.EventLoopGroup) StandardCharsets(java.nio.charset.StandardCharsets) Test(org.junit.jupiter.api.Test) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) AfterEach(org.junit.jupiter.api.AfterEach) SubscriptionResponseMessage(software.amazon.awssdk.aws.greengrass.model.SubscriptionResponseMessage) CreateLocalDeploymentRequest(software.amazon.awssdk.aws.greengrass.model.CreateLocalDeploymentRequest) GeneratedAbstractSubscribeToTopicOperationHandler(greengrass.GeneratedAbstractSubscribeToTopicOperationHandler) CreateLocalDeploymentResponse(software.amazon.awssdk.aws.greengrass.model.CreateLocalDeploymentResponse) Optional(java.util.Optional) SubscribeToTopicRequest(software.amazon.awssdk.aws.greengrass.model.SubscribeToTopicRequest) SubscribeToTopicResponse(software.amazon.awssdk.aws.greengrass.model.SubscribeToTopicResponse) GreengrassEventStreamConnectMessage(software.amazon.awssdk.eventstreamrpc.GreengrassEventStreamConnectMessage) SubscribeToTopicResponseHandler(software.amazon.awssdk.aws.greengrass.SubscribeToTopicResponseHandler) GreengrassCoreIPCClientV2(software.amazon.awssdk.aws.greengrass.GreengrassCoreIPCClientV2) StreamResponseHandler(software.amazon.awssdk.eventstreamrpc.StreamResponseHandler) CreateLocalDeploymentRequest(software.amazon.awssdk.aws.greengrass.model.CreateLocalDeploymentRequest) CompletableFuture(java.util.concurrent.CompletableFuture) CreateLocalDeploymentResponse(software.amazon.awssdk.aws.greengrass.model.CreateLocalDeploymentResponse) SubscriptionResponseMessage(software.amazon.awssdk.aws.greengrass.model.SubscriptionResponseMessage) SubscribeToTopicResponse(software.amazon.awssdk.aws.greengrass.model.SubscribeToTopicResponse) SubscribeToTopicRequest(software.amazon.awssdk.aws.greengrass.model.SubscribeToTopicRequest) Test(org.junit.jupiter.api.Test)

Aggregations

SubscribeToTopicRequest (software.amazon.awssdk.aws.greengrass.model.SubscribeToTopicRequest)9 Test (org.junit.jupiter.api.Test)7 SocketOptions (software.amazon.awssdk.crt.io.SocketOptions)7 ExecutionException (java.util.concurrent.ExecutionException)6 SubscribeToTopicResponse (software.amazon.awssdk.aws.greengrass.model.SubscribeToTopicResponse)6 GreengrassCoreIPCClient (software.amazon.awssdk.aws.greengrass.GreengrassCoreIPCClient)5 SubscriptionResponseMessage (software.amazon.awssdk.aws.greengrass.model.SubscriptionResponseMessage)5 EventStreamRPCConnection (software.amazon.awssdk.eventstreamrpc.EventStreamRPCConnection)5 IOException (java.io.IOException)4 CountDownLatch (java.util.concurrent.CountDownLatch)3 UnauthorizedError (software.amazon.awssdk.aws.greengrass.model.UnauthorizedError)3 Gson (com.google.gson.Gson)2 GeneratedAbstractCreateLocalDeploymentOperationHandler (greengrass.GeneratedAbstractCreateLocalDeploymentOperationHandler)2 GeneratedAbstractSubscribeToTopicOperationHandler (greengrass.GeneratedAbstractSubscribeToTopicOperationHandler)2 GreengrassCoreIPCService (greengrass.GreengrassCoreIPCService)2 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)2 BeforeEach (org.junit.jupiter.api.BeforeEach)2 BinaryMessage (software.amazon.awssdk.aws.greengrass.model.BinaryMessage)2 CreateLocalDeploymentRequest (software.amazon.awssdk.aws.greengrass.model.CreateLocalDeploymentRequest)2 CreateLocalDeploymentResponse (software.amazon.awssdk.aws.greengrass.model.CreateLocalDeploymentResponse)2