Search in sources :

Example 1 with AwsIotMqttConnectionBuilder

use of software.amazon.awssdk.iot.AwsIotMqttConnectionBuilder in project aws-greengrass-nucleus by aws-greengrass.

the class SecurityServiceTest method GIVEN_mqtt_connection_provider_registered_WHEN_get_mqtt_builder_THEN_delegate_call_to_service_provider.

@SuppressWarnings("PMD.CloseResource")
@Test
void GIVEN_mqtt_connection_provider_registered_WHEN_get_mqtt_builder_THEN_delegate_call_to_service_provider() throws Exception {
    when(mockConnectionProvider.supportedKeyType()).thenReturn("PKCS11");
    String keyUriStr = "pkcs11:object=key-label";
    String certUriStr = "file:///path/to/certificate";
    URI keyUri = new URI(keyUriStr);
    URI certificateUri = new URI(certUriStr);
    AwsIotMqttConnectionBuilder mockBuilder = mock(AwsIotMqttConnectionBuilder.class);
    when(mockConnectionProvider.getMqttConnectionBuilder(keyUri, certificateUri)).thenReturn(mockBuilder);
    Topic keyTopic = mock(Topic.class);
    when(keyTopic.getOnce()).thenReturn(keyUriStr);
    when(deviceConfiguration.getPrivateKeyFilePath()).thenReturn(keyTopic);
    Topic certTopic = mock(Topic.class);
    when(certTopic.getOnce()).thenReturn(certUriStr);
    when(deviceConfiguration.getCertificateFilePath()).thenReturn(certTopic);
    service.registerMqttConnectionProvider(mockConnectionProvider);
    AwsIotMqttConnectionBuilder builder = service.getDeviceIdentityMqttConnectionBuilder();
    assertThat(builder, Is.is(mockBuilder));
}
Also used : AwsIotMqttConnectionBuilder(software.amazon.awssdk.iot.AwsIotMqttConnectionBuilder) CaseInsensitiveString(com.aws.greengrass.config.CaseInsensitiveString) Matchers.containsString(org.hamcrest.Matchers.containsString) Topic(com.aws.greengrass.config.Topic) URI(java.net.URI) EncryptionUtilsTest(com.aws.greengrass.util.EncryptionUtilsTest) Test(org.junit.jupiter.api.Test)

Example 2 with AwsIotMqttConnectionBuilder

use of software.amazon.awssdk.iot.AwsIotMqttConnectionBuilder in project aws-greengrass-nucleus by aws-greengrass.

the class SecurityServiceTest method GIVEN_mqtt_connection_provider_registered_but_not_available_WHEN_get_mqtt_builder_THEN_retry.

@SuppressWarnings("PMD.CloseResource")
@Test
void GIVEN_mqtt_connection_provider_registered_but_not_available_WHEN_get_mqtt_builder_THEN_retry(ExtensionContext context) throws Exception {
    ignoreExceptionOfType(context, ServiceUnavailableException.class);
    when(mockConnectionProvider.supportedKeyType()).thenReturn("PKCS11");
    String keyUriStr = "pkcs11:object=key-label";
    String certUriStr = "file:///path/to/certificate";
    URI keyUri = new URI(keyUriStr);
    URI certificateUri = new URI(certUriStr);
    AwsIotMqttConnectionBuilder mockBuilder = mock(AwsIotMqttConnectionBuilder.class);
    when(mockConnectionProvider.getMqttConnectionBuilder(keyUri, certificateUri)).thenThrow(ServiceUnavailableException.class).thenReturn(mockBuilder);
    Topic keyTopic = mock(Topic.class);
    when(keyTopic.getOnce()).thenReturn(keyUriStr);
    when(deviceConfiguration.getPrivateKeyFilePath()).thenReturn(keyTopic);
    Topic certTopic = mock(Topic.class);
    when(certTopic.getOnce()).thenReturn(certUriStr);
    when(deviceConfiguration.getCertificateFilePath()).thenReturn(certTopic);
    service.registerMqttConnectionProvider(mockConnectionProvider);
    AwsIotMqttConnectionBuilder builder = service.getDeviceIdentityMqttConnectionBuilder();
    assertThat(builder, Is.is(mockBuilder));
    verify(mockConnectionProvider, times(2)).getMqttConnectionBuilder(keyUri, certificateUri);
}
Also used : AwsIotMqttConnectionBuilder(software.amazon.awssdk.iot.AwsIotMqttConnectionBuilder) CaseInsensitiveString(com.aws.greengrass.config.CaseInsensitiveString) Matchers.containsString(org.hamcrest.Matchers.containsString) ServiceUnavailableException(com.aws.greengrass.security.exceptions.ServiceUnavailableException) Topic(com.aws.greengrass.config.Topic) URI(java.net.URI) EncryptionUtilsTest(com.aws.greengrass.util.EncryptionUtilsTest) Test(org.junit.jupiter.api.Test)

Example 3 with AwsIotMqttConnectionBuilder

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

the class Pkcs11Connect method main.

public static void main(String[] args) {
    cmdUtils = new CommandLineUtils();
    cmdUtils.registerProgramName("Pkcs11PubSub");
    cmdUtils.addCommonMQTTCommands();
    cmdUtils.registerCommand("cert", "<path>", "Path to your client certificate in PEM format.");
    cmdUtils.registerCommand("client_id", "<int>", "Client id to use (optional, default='test-*').");
    cmdUtils.registerCommand("port", "<int>", "Port to connect to on the endpoint (optional, default='8883').");
    cmdUtils.registerCommand("pkcs11_lib", "<path>", "Path to PKCS#11 library.");
    cmdUtils.registerCommand("pin", "<int>", "User PIN for logging into PKCS#11 token.");
    cmdUtils.registerCommand("token_label", "<str>", "Label of PKCS#11 token to use (optional).");
    cmdUtils.registerCommand("slot_id", "<int>", "Slot ID containing PKCS#11 token to use (optional).");
    cmdUtils.registerCommand("key_label", "<str>", "Label of private key on the PKCS#11 token (optional).");
    cmdUtils.registerCommand("help", "", "Prints this message");
    cmdUtils.sendArguments(args);
    if (cmdUtils.hasCommand("help")) {
        cmdUtils.printHelp();
        System.exit(1);
    }
    String endpoint = cmdUtils.getCommandRequired("endpoint", "");
    String certPath = cmdUtils.getCommandRequired("cert", "");
    String CaPath = cmdUtils.getCommandOrDefault("ca_file", "");
    String clientId = cmdUtils.getCommandOrDefault("client_id", "test-" + UUID.randomUUID().toString());
    int port = Integer.parseInt(cmdUtils.getCommandOrDefault("port", "8883"));
    String pkcs11LibPath = cmdUtils.getCommandRequired("pkcs11_lib", "");
    String pkcs11UserPin = cmdUtils.getCommandRequired("pin", "");
    String pkcs11TokenLabel = cmdUtils.getCommandOrDefault("key_label", "");
    Long pkcs11SlotId = null;
    if (cmdUtils.hasCommand("slot_id")) {
        Long.parseLong(cmdUtils.getCommandOrDefault("slot_id", "-1"));
    }
    String pkcs11KeyLabel = cmdUtils.getCommandOrDefault("key_label", "");
    MqttClientConnectionEvents callbacks = new MqttClientConnectionEvents() {

        @Override
        public void onConnectionInterrupted(int errorCode) {
            if (errorCode != 0) {
                System.out.println("Connection interrupted: " + errorCode + ": " + CRT.awsErrorString(errorCode));
            }
        }

        @Override
        public void onConnectionResumed(boolean sessionPresent) {
            System.out.println("Connection resumed: " + (sessionPresent ? "existing session" : "clean session"));
        }
    };
    // Load PKCS#11 library
    try (Pkcs11Lib pkcs11Lib = new Pkcs11Lib(pkcs11LibPath);
        TlsContextPkcs11Options pkcs11Options = new TlsContextPkcs11Options(pkcs11Lib)) {
        pkcs11Options.withCertificateFilePath(certPath);
        pkcs11Options.withUserPin(pkcs11UserPin);
        if (pkcs11TokenLabel != null && pkcs11TokenLabel != "") {
            pkcs11Options.withTokenLabel(pkcs11TokenLabel);
        }
        if (pkcs11SlotId != null) {
            pkcs11Options.withSlotId(pkcs11SlotId);
        }
        if (pkcs11KeyLabel != null && pkcs11KeyLabel != "") {
            pkcs11Options.withPrivateKeyObjectLabel(pkcs11KeyLabel);
        }
        try (AwsIotMqttConnectionBuilder builder = AwsIotMqttConnectionBuilder.newMtlsPkcs11Builder(pkcs11Options)) {
            if (CaPath != null) {
                builder.withCertificateAuthorityFromPath(null, CaPath);
            }
            builder.withConnectionEventCallbacks(callbacks).withClientId(clientId).withEndpoint(endpoint).withPort((short) port).withCleanSession(true).withProtocolOperationTimeoutMs(60000);
            try (MqttClientConnection connection = builder.build()) {
                CompletableFuture<Boolean> connected = connection.connect();
                try {
                    boolean sessionPresent = connected.get();
                    System.out.println("Connected to " + (!sessionPresent ? "new" : "existing") + " session!");
                } catch (Exception ex) {
                    throw new RuntimeException("Exception occurred during connect", ex);
                }
                System.out.println("Disconnecting...");
                CompletableFuture<Void> disconnected = connection.disconnect();
                disconnected.get();
                System.out.println("Disconnected.");
            }
        } catch (CrtRuntimeException | InterruptedException | ExecutionException ex) {
            onApplicationFailure(ex);
        }
    }
    CrtResource.waitForNoResources();
    System.out.println("Complete!");
}
Also used : ExecutionException(java.util.concurrent.ExecutionException) CommandLineUtils(utils.commandlineutils.CommandLineUtils) AwsIotMqttConnectionBuilder(software.amazon.awssdk.iot.AwsIotMqttConnectionBuilder) ExecutionException(java.util.concurrent.ExecutionException)

Example 4 with AwsIotMqttConnectionBuilder

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

the class CommandLineOption method buildWebsocketMQTTConnection.

public MqttClientConnection buildWebsocketMQTTConnection(MqttClientConnectionEvents callbacks) {
    try {
        AwsIotMqttConnectionBuilder builder = AwsIotMqttConnectionBuilder.newMtlsBuilderFromPath(null, null);
        buildConnectionSetupCAFileDefaults(builder);
        buildConnectionSetupConnectionDefaults(builder, callbacks);
        buildConnectionSetupProxyDefaults(builder);
        builder.withWebsockets(true);
        builder.withWebsocketSigningRegion(getCommandRequired(m_cmd_signing_region, ""));
        return builder.build();
    } catch (CrtRuntimeException ex) {
        return null;
    }
}
Also used : AwsIotMqttConnectionBuilder(software.amazon.awssdk.iot.AwsIotMqttConnectionBuilder)

Example 5 with AwsIotMqttConnectionBuilder

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

the class CommandLineOption method buildPKCS11MQTTConnection.

public MqttClientConnection buildPKCS11MQTTConnection(MqttClientConnectionEvents callbacks) {
    try {
        Pkcs11Lib pkcs11Lib = new Pkcs11Lib(getCommandRequired(m_cmd_pkcs11_lib, ""));
        TlsContextPkcs11Options pkcs11Options = new TlsContextPkcs11Options(pkcs11Lib);
        pkcs11Options.withCertificateFilePath(getCommandRequired(m_cmd_cert_file, ""));
        pkcs11Options.withUserPin(getCommandRequired(m_cmd_pkcs11_pin, ""));
        if (hasCommand(m_cmd_pkcs11_token)) {
            pkcs11Options.withTokenLabel(getCommand(m_cmd_pkcs11_token));
        }
        if (hasCommand(m_cmd_pkcs11_slot)) {
            pkcs11Options.withSlotId(Long.parseLong(getCommand(m_cmd_pkcs11_slot)));
        }
        if (hasCommand(m_cmd_pkcs11_key)) {
            pkcs11Options.withPrivateKeyObjectLabel(getCommand(m_cmd_pkcs11_key));
        }
        AwsIotMqttConnectionBuilder builder = AwsIotMqttConnectionBuilder.newMtlsPkcs11Builder(pkcs11Options);
        buildConnectionSetupCAFileDefaults(builder);
        buildConnectionSetupConnectionDefaults(builder, callbacks);
        return builder.build();
    } catch (CrtRuntimeException ex) {
        return null;
    }
}
Also used : AwsIotMqttConnectionBuilder(software.amazon.awssdk.iot.AwsIotMqttConnectionBuilder)

Aggregations

AwsIotMqttConnectionBuilder (software.amazon.awssdk.iot.AwsIotMqttConnectionBuilder)15 ExecutionException (java.util.concurrent.ExecutionException)7 CrtRuntimeException (software.amazon.awssdk.crt.CrtRuntimeException)5 MqttClientConnection (software.amazon.awssdk.crt.mqtt.MqttClientConnection)4 CaseInsensitiveString (com.aws.greengrass.config.CaseInsensitiveString)2 Topic (com.aws.greengrass.config.Topic)2 EncryptionUtilsTest (com.aws.greengrass.util.EncryptionUtilsTest)2 URI (java.net.URI)2 Matchers.containsString (org.hamcrest.Matchers.containsString)2 Test (org.junit.jupiter.api.Test)2 CommandLineUtils (utils.commandlineutils.CommandLineUtils)2 ServiceUnavailableException (com.aws.greengrass.security.exceptions.ServiceUnavailableException)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 CompletableFuture (java.util.concurrent.CompletableFuture)1 X509CredentialsProvider (software.amazon.awssdk.crt.auth.credentials.X509CredentialsProvider)1 HttpProxyOptions (software.amazon.awssdk.crt.http.HttpProxyOptions)1 MqttException (software.amazon.awssdk.crt.mqtt.MqttException)1 MqttMessage (software.amazon.awssdk.crt.mqtt.MqttMessage)1 ConnectivityInfo (software.amazon.awssdk.iot.discovery.model.ConnectivityInfo)1 DiscoverResponse (software.amazon.awssdk.iot.discovery.model.DiscoverResponse)1