Search in sources :

Example 1 with UnauthorizedError

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

the class IPCPubSubRemovalTest method GIVEN_pubsubclient_WHEN_authorized_THEN_ACL_child_removed_THEN_updates.

@Test
void GIVEN_pubsubclient_WHEN_authorized_THEN_ACL_child_removed_THEN_updates() throws Exception {
    try (EventStreamRPCConnection connection = IPCTestUtils.getEventStreamRpcConnection(kernel, "DoAll1")) {
        GreengrassCoreIPCClient ipcClient = new GreengrassCoreIPCClient(connection);
        assertTrue(kernel.getContext().get(AuthorizationModule.class).isPresent(TOKEN_EXCHANGE_SERVICE_TOPICS, TES_DEFAULT_POLICY));
        Pair<CompletableFuture<Void>, Consumer<byte[]>> cb = asyncAssertOnConsumer((m) -> {
            assertEquals("some message", new String(m, StandardCharsets.UTF_8));
        });
        subscribeToTopicOveripcForBinaryMessages(ipcClient, "a", cb.getRight());
        publishToTopicOverIpcAsBinaryMessage(ipcClient, "a", "some message");
        cb.getLeft().get(TIMEOUT_FOR_PUBSUB_SECONDS, TimeUnit.SECONDS);
        Topics serviceTopic = kernel.findServiceTopic("DoAll1");
        Topics parameters = serviceTopic.findTopics(CONFIGURATION_CONFIG_KEY);
        Topic acl = parameters.find(ACCESS_CONTROL_NAMESPACE_TOPIC, "aws.greengrass.ipc.pubsub", "policyId5", "operations");
        if (acl != null) {
            acl.withValue(Collections.emptyList());
        }
        // Block until events are completed
        kernel.getContext().waitForPublishQueueToClear();
        assertTrue(kernel.getContext().get(AuthorizationModule.class).isPresent(TOKEN_EXCHANGE_SERVICE_TOPICS, TES_DEFAULT_POLICY));
        // Now the authorization policies should have been removed and these should fail
        ExecutionException executionException = assertThrows(ExecutionException.class, () -> subscribeToTopicOveripcForBinaryMessages(ipcClient, "a", cb.getRight()));
        assertTrue(executionException.getCause() instanceof UnauthorizedError);
        ExecutionException executionException1 = assertThrows(ExecutionException.class, () -> publishToTopicOverIpcAsBinaryMessage(ipcClient, "a", "some message"));
        assertTrue(executionException1.getCause() instanceof UnauthorizedError);
        serviceTopic = kernel.findServiceTopic("DoAll1");
        parameters = serviceTopic.findTopics(CONFIGURATION_CONFIG_KEY);
        Topics aclTopics = parameters.findTopics(ACCESS_CONTROL_NAMESPACE_TOPIC);
        if (aclTopics != null) {
            aclTopics.remove();
        }
        // Block until events are completed
        kernel.getContext().waitForPublishQueueToClear();
        assertTrue(kernel.getContext().get(AuthorizationModule.class).isPresent(TOKEN_EXCHANGE_SERVICE_TOPICS, TES_DEFAULT_POLICY));
        // Now the authorization policies should have been removed and these should fail
        executionException = assertThrows(ExecutionException.class, () -> subscribeToTopicOveripcForBinaryMessages(ipcClient, "a", cb.getRight()));
        assertTrue(executionException.getCause() instanceof UnauthorizedError);
        executionException1 = assertThrows(ExecutionException.class, () -> publishToTopicOverIpcAsBinaryMessage(ipcClient, "a", "some message"));
        assertTrue(executionException1.getCause() instanceof UnauthorizedError);
    }
}
Also used : CompletableFuture(java.util.concurrent.CompletableFuture) Topics(com.aws.greengrass.config.Topics) TestUtils.asyncAssertOnConsumer(com.aws.greengrass.testcommons.testutilities.TestUtils.asyncAssertOnConsumer) Consumer(java.util.function.Consumer) GreengrassCoreIPCClient(software.amazon.awssdk.aws.greengrass.GreengrassCoreIPCClient) EventStreamRPCConnection(software.amazon.awssdk.eventstreamrpc.EventStreamRPCConnection) Topic(com.aws.greengrass.config.Topic) ExecutionException(java.util.concurrent.ExecutionException) UnauthorizedError(software.amazon.awssdk.aws.greengrass.model.UnauthorizedError) Test(org.junit.jupiter.api.Test)

Example 2 with UnauthorizedError

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

the class IPCPubSubRemovalTest method GIVEN_pubsubclient_WHEN_authorized_THEN_component_removed_via_deployment_THEN_updates.

@Test
void GIVEN_pubsubclient_WHEN_authorized_THEN_component_removed_via_deployment_THEN_updates(ExtensionContext context) throws Exception {
    try (EventStreamRPCConnection connection = IPCTestUtils.getEventStreamRpcConnection(kernel, "SubscribeAndPublish")) {
        GreengrassCoreIPCClient ipcClient = new GreengrassCoreIPCClient(connection);
        Pair<CompletableFuture<Void>, Consumer<byte[]>> cb = asyncAssertOnConsumer((m) -> {
            assertEquals("some message", new String(m, StandardCharsets.UTF_8));
        }, -1);
        Permission policyId1 = Permission.builder().principal("SubscribeAndPublish").operation("*").resource("*").build();
        Permission policyId2 = Permission.builder().principal("PublishNotSubscribe").operation("aws.greengrass#PublishToTopic").resource("*").build();
        assertTrue(kernel.getContext().get(AuthorizationModule.class).isPresent(PUB_SUB_SERVICE_NAME, policyId1));
        assertTrue(kernel.getContext().get(AuthorizationModule.class).isPresent(PUB_SUB_SERVICE_NAME, policyId2));
        assertTrue(kernel.getContext().get(AuthorizationModule.class).isPresent(TOKEN_EXCHANGE_SERVICE_TOPICS, TES_DEFAULT_POLICY));
        subscribeToTopicOveripcForBinaryMessages(ipcClient, "a", cb.getRight());
        publishToTopicOverIpcAsBinaryMessage(ipcClient, "a", "some message");
        cb.getLeft().get(TIMEOUT_FOR_PUBSUB_SECONDS, TimeUnit.SECONDS);
        // Remove component SubscribeAndPublish
        GreengrassService subscribeAndPublish = kernel.locate("SubscribeAndPublish");
        subscribeAndPublish.close().get(1, TimeUnit.MINUTES);
        subscribeAndPublish.getConfig().remove();
        kernel.getContext().waitForPublishQueueToClear();
        assertFalse(kernel.getContext().get(AuthorizationModule.class).isPresent(PUB_SUB_SERVICE_NAME, policyId1));
        // GG_NEEDS_REVIEW: TODO: convert all these integ tests to use only recipe merging instead of loading a kernel config file
        // Otherwise the removal of "SubscribeAndPublish" also inadvertently results in the "PublishNotSubscribe"
        // component (and all other components) and its policies being removed, since it is not part of the deployment.
        // Hence the next line is commented out
        // assertTrue(kernel.getContext().get(AuthorizationModule.class).isPresent(PUB_SUB_SERVICE_NAME,policyId2));
        assertTrue(kernel.getContext().get(AuthorizationModule.class).isPresent(TOKEN_EXCHANGE_SERVICE_TOPICS, TES_DEFAULT_POLICY));
        // Now the authorization policies should have been removed and these should fail
        ExecutionException e = assertThrows(ExecutionException.class, () -> subscribeToTopicOveripcForBinaryMessages(ipcClient, "a", cb.getRight()));
        assertTrue(e.getCause() instanceof UnauthorizedError);
        e = assertThrows(ExecutionException.class, () -> publishToTopicOverIpcAsBinaryMessage(ipcClient, "a", "some message"));
    }
}
Also used : CompletableFuture(java.util.concurrent.CompletableFuture) TestUtils.asyncAssertOnConsumer(com.aws.greengrass.testcommons.testutilities.TestUtils.asyncAssertOnConsumer) Consumer(java.util.function.Consumer) GreengrassService(com.aws.greengrass.lifecyclemanager.GreengrassService) GreengrassCoreIPCClient(software.amazon.awssdk.aws.greengrass.GreengrassCoreIPCClient) EventStreamRPCConnection(software.amazon.awssdk.eventstreamrpc.EventStreamRPCConnection) Permission(com.aws.greengrass.authorization.Permission) ExecutionException(java.util.concurrent.ExecutionException) UnauthorizedError(software.amazon.awssdk.aws.greengrass.model.UnauthorizedError) Test(org.junit.jupiter.api.Test)

Example 3 with UnauthorizedError

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

the class IPCPubSubRemovalTest method GIVEN_pubsubclient_WHEN_authorized_THEN_parameters_child_removed_THEN_updates.

@Test
void GIVEN_pubsubclient_WHEN_authorized_THEN_parameters_child_removed_THEN_updates() throws Exception {
    try (EventStreamRPCConnection connection = IPCTestUtils.getEventStreamRpcConnection(kernel, "DoAll2")) {
        GreengrassCoreIPCClient ipcClient = new GreengrassCoreIPCClient(connection);
        assertTrue(kernel.getContext().get(AuthorizationModule.class).isPresent(TOKEN_EXCHANGE_SERVICE_TOPICS, TES_DEFAULT_POLICY));
        Pair<CompletableFuture<Void>, Consumer<byte[]>> cb = asyncAssertOnConsumer((m) -> {
            assertEquals("some message", new String(m, StandardCharsets.UTF_8));
        });
        // this should succeed
        subscribeToTopicOveripcForBinaryMessages(ipcClient, "a", cb.getRight());
        publishToTopicOverIpcAsBinaryMessage(ipcClient, "a", "some message");
        cb.getLeft().get(TIMEOUT_FOR_PUBSUB_SECONDS, TimeUnit.SECONDS);
        Topics serviceTopic = kernel.findServiceTopic("DoAll2");
        Topics parameters = serviceTopic.findTopics(CONFIGURATION_CONFIG_KEY);
        if (parameters != null) {
            parameters.remove();
        }
        // Block until events are completed
        kernel.getContext().waitForPublishQueueToClear();
        assertTrue(kernel.getContext().get(AuthorizationModule.class).isPresent(TOKEN_EXCHANGE_SERVICE_TOPICS, TES_DEFAULT_POLICY));
        // Now the authorization policies should have been removed and these should fail
        ExecutionException e = assertThrows(ExecutionException.class, () -> subscribeToTopicOveripcForBinaryMessages(ipcClient, "a", cb.getRight()));
        assertTrue(e.getCause() instanceof UnauthorizedError);
        e = assertThrows(ExecutionException.class, () -> publishToTopicOverIpcAsBinaryMessage(ipcClient, "a", "some message"));
        assertTrue(e.getCause() instanceof UnauthorizedError);
    }
}
Also used : CompletableFuture(java.util.concurrent.CompletableFuture) Topics(com.aws.greengrass.config.Topics) TestUtils.asyncAssertOnConsumer(com.aws.greengrass.testcommons.testutilities.TestUtils.asyncAssertOnConsumer) Consumer(java.util.function.Consumer) 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) Test(org.junit.jupiter.api.Test)

Example 4 with UnauthorizedError

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

the class IPCPubSubRemovalTest method GIVEN_pubsubclient_WHEN_service_removed_and_added_THEN_fail_and_succeed.

@Test
void GIVEN_pubsubclient_WHEN_service_removed_and_added_THEN_fail_and_succeed() throws Exception {
    try (EventStreamRPCConnection connection = IPCTestUtils.getEventStreamRpcConnection(kernel, "SubscribeAndPublish")) {
        GreengrassCoreIPCClient ipcClient = new GreengrassCoreIPCClient(connection);
        assertTrue(kernel.getContext().get(AuthorizationModule.class).isPresent(TOKEN_EXCHANGE_SERVICE_TOPICS, TES_DEFAULT_POLICY));
        Pair<CompletableFuture<Void>, Consumer<byte[]>> cb = asyncAssertOnConsumer((m) -> {
            assertEquals("some message", new String(m, StandardCharsets.UTF_8));
        }, -1);
        Permission policyId1 = Permission.builder().principal("SubscribeAndPublish").operation("*").resource("*").build();
        Permission policyId2 = Permission.builder().principal("PublishNotSubscribe").operation("aws.greengrass#PublishToTopic").resource("*").build();
        assertTrue(kernel.getContext().get(AuthorizationModule.class).isPresent(PUB_SUB_SERVICE_NAME, policyId1));
        assertTrue(kernel.getContext().get(AuthorizationModule.class).isPresent(PUB_SUB_SERVICE_NAME, policyId2));
        subscribeToTopicOveripcForBinaryMessages(ipcClient, "a", cb.getRight());
        publishToTopicOverIpcAsBinaryMessage(ipcClient, "a", "some message");
        cb.getLeft().get(TIMEOUT_FOR_PUBSUB_SECONDS, TimeUnit.SECONDS);
        // Remove the service topic
        Topics serviceTopic = kernel.findServiceTopic("SubscribeAndPublish");
        if (serviceTopic != null) {
            serviceTopic.remove();
        }
        kernel.getContext().waitForPublishQueueToClear();
        assertFalse(kernel.getContext().get(AuthorizationModule.class).isPresent(PUB_SUB_SERVICE_NAME, policyId1));
        assertTrue(kernel.getContext().get(AuthorizationModule.class).isPresent(PUB_SUB_SERVICE_NAME, policyId2));
        ExecutionException e = assertThrows(ExecutionException.class, () -> subscribeToTopicOveripcForBinaryMessages(ipcClient, "a", cb.getRight()));
        assertTrue(e.getCause() instanceof UnauthorizedError);
        e = assertThrows(ExecutionException.class, () -> publishToTopicOverIpcAsBinaryMessage(ipcClient, "a", "some message"));
        assertTrue(e.getCause() instanceof UnauthorizedError);
        // Reload the kernel with the service and correct authorization policy
        kernel.getConfig().read(new URL(IPCPubSubTest.class.getResource("pubsub.yaml").toString()), false);
        kernel.getContext().waitForPublishQueueToClear();
        assertTrue(kernel.getContext().get(AuthorizationModule.class).isPresent(PUB_SUB_SERVICE_NAME, policyId1));
        assertTrue(kernel.getContext().get(AuthorizationModule.class).isPresent(PUB_SUB_SERVICE_NAME, policyId2));
        assertTrue(kernel.getContext().get(AuthorizationModule.class).isPresent(TOKEN_EXCHANGE_SERVICE_TOPICS, TES_DEFAULT_POLICY));
        // now this should succeed
        subscribeToTopicOveripcForBinaryMessages(ipcClient, "a", cb.getRight());
        publishToTopicOverIpcAsBinaryMessage(ipcClient, "a", "some message");
        cb.getLeft().get(TIMEOUT_FOR_PUBSUB_SECONDS, TimeUnit.SECONDS);
    }
}
Also used : CompletableFuture(java.util.concurrent.CompletableFuture) Topics(com.aws.greengrass.config.Topics) TestUtils.asyncAssertOnConsumer(com.aws.greengrass.testcommons.testutilities.TestUtils.asyncAssertOnConsumer) Consumer(java.util.function.Consumer) GreengrassCoreIPCClient(software.amazon.awssdk.aws.greengrass.GreengrassCoreIPCClient) EventStreamRPCConnection(software.amazon.awssdk.eventstreamrpc.EventStreamRPCConnection) Permission(com.aws.greengrass.authorization.Permission) ExecutionException(java.util.concurrent.ExecutionException) UnauthorizedError(software.amazon.awssdk.aws.greengrass.model.UnauthorizedError) URL(java.net.URL) Test(org.junit.jupiter.api.Test)

Example 5 with UnauthorizedError

use of software.amazon.awssdk.aws.greengrass.model.UnauthorizedError 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)

Aggregations

ExecutionException (java.util.concurrent.ExecutionException)12 Test (org.junit.jupiter.api.Test)12 GreengrassCoreIPCClient (software.amazon.awssdk.aws.greengrass.GreengrassCoreIPCClient)12 UnauthorizedError (software.amazon.awssdk.aws.greengrass.model.UnauthorizedError)12 EventStreamRPCConnection (software.amazon.awssdk.eventstreamrpc.EventStreamRPCConnection)12 TestUtils.asyncAssertOnConsumer (com.aws.greengrass.testcommons.testutilities.TestUtils.asyncAssertOnConsumer)7 CompletableFuture (java.util.concurrent.CompletableFuture)7 Consumer (java.util.function.Consumer)7 Topics (com.aws.greengrass.config.Topics)6 SocketOptions (software.amazon.awssdk.crt.io.SocketOptions)4 Permission (com.aws.greengrass.authorization.Permission)3 SubscribeToTopicRequest (software.amazon.awssdk.aws.greengrass.model.SubscribeToTopicRequest)3 UpdateBehaviorTree (com.aws.greengrass.config.UpdateBehaviorTree)2 Map (java.util.Map)2 Topic (com.aws.greengrass.config.Topic)1 GreengrassService (com.aws.greengrass.lifecyclemanager.GreengrassService)1 IOException (java.io.IOException)1 URL (java.net.URL)1 CountDownLatch (java.util.concurrent.CountDownLatch)1 Order (org.junit.jupiter.api.Order)1