use of com.microsoft.azure.sdk.iot.provisioning.device.internal.exceptions.ProvisioningDeviceClientException in project azure-iot-sdk-java by Azure.
the class ProvisioningAmqpOperationsTest method sendStatusMessageThrowsOnSendAmqpMessage.
// SRS_ProvisioningAmqpOperations_07_018: [This method shall throw ProvisioningDeviceClientException if any failure is encountered.]
@Test(expected = ProvisioningDeviceClientException.class)
public void sendStatusMessageThrowsOnSendAmqpMessage() throws ProvisioningDeviceClientException, IOException, InterruptedException {
// arrange
ProvisioningAmqpOperations provisioningAmqpOperations = new ProvisioningAmqpOperations(TEST_SCOPE_ID, TEST_HOST_NAME);
new NonStrictExpectations() {
{
mockedAmqpConnection.setListener((AmqpListener) any);
mockedAmqpConnection.open();
}
};
provisioningAmqpOperations.open(TEST_REGISTRATION_ID, mockedSSLContext, null, false);
new NonStrictExpectations() {
{
new AmqpMessage();
result = new Exception();
}
};
// act
provisioningAmqpOperations.sendStatusMessage(TEST_OPERATION_ID, mockedResponseCallback, null);
// assert
}
use of com.microsoft.azure.sdk.iot.provisioning.device.internal.exceptions.ProvisioningDeviceClientException in project azure-iot-sdk-java by Azure.
the class ProvisioningTpmSample method main.
public static void main(String[] args) throws Exception {
System.out.println("Starting...");
System.out.println("Beginning setup.");
SecurityProviderTpm securityClientTPMEmulator = null;
Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8.name());
DeviceClient deviceClient = null;
try {
securityClientTPMEmulator = new SecurityProviderTPMEmulator();
System.out.println("Endorsement Key : \n" + new String(encodeBase64(securityClientTPMEmulator.getEndorsementKey()), StandardCharsets.UTF_8));
System.out.println("Registration Id : \n" + securityClientTPMEmulator.getRegistrationId());
System.out.println("Please visit Azure Portal (https://portal.azure.com/) and create a TPM Individual Enrollment with the information above i.e EndorsementKey and RegistrationId \n" + "Press enter when you are ready to run registration after enrolling with the service");
scanner.nextLine();
} catch (SecurityProviderException e) {
e.printStackTrace();
}
ProvisioningDeviceClient provisioningDeviceClient = null;
try {
ProvisioningStatus provisioningStatus = new ProvisioningStatus();
provisioningDeviceClient = ProvisioningDeviceClient.create(GLOBAL_ENDPOINT, SCOPE_ID, PROVISIONING_DEVICE_CLIENT_TRANSPORT_PROTOCOL, securityClientTPMEmulator);
provisioningDeviceClient.registerDevice(new ProvisioningDeviceClientRegistrationCallbackImpl(), provisioningStatus);
while (provisioningStatus.provisioningDeviceClientRegistrationInfoClient.getProvisioningDeviceClientStatus() != ProvisioningDeviceClientStatus.PROVISIONING_DEVICE_STATUS_ASSIGNED) {
if (provisioningStatus.provisioningDeviceClientRegistrationInfoClient.getProvisioningDeviceClientStatus() == ProvisioningDeviceClientStatus.PROVISIONING_DEVICE_STATUS_ERROR || provisioningStatus.provisioningDeviceClientRegistrationInfoClient.getProvisioningDeviceClientStatus() == ProvisioningDeviceClientStatus.PROVISIONING_DEVICE_STATUS_DISABLED || provisioningStatus.provisioningDeviceClientRegistrationInfoClient.getProvisioningDeviceClientStatus() == ProvisioningDeviceClientStatus.PROVISIONING_DEVICE_STATUS_FAILED) {
provisioningStatus.exception.printStackTrace();
System.out.println("Registration error, bailing out");
break;
}
System.out.println("Waiting for Provisioning Service to register");
Thread.sleep(MAX_TIME_TO_WAIT_FOR_REGISTRATION);
}
if (provisioningStatus.provisioningDeviceClientRegistrationInfoClient.getProvisioningDeviceClientStatus() == ProvisioningDeviceClientStatus.PROVISIONING_DEVICE_STATUS_ASSIGNED) {
System.out.println("IotHUb Uri : " + provisioningStatus.provisioningDeviceClientRegistrationInfoClient.getIothubUri());
System.out.println("Device ID : " + provisioningStatus.provisioningDeviceClientRegistrationInfoClient.getDeviceId());
// connect to iothub
String iotHubUri = provisioningStatus.provisioningDeviceClientRegistrationInfoClient.getIothubUri();
String deviceId = provisioningStatus.provisioningDeviceClientRegistrationInfoClient.getDeviceId();
try {
deviceClient = DeviceClient.createFromSecurityProvider(iotHubUri, deviceId, securityClientTPMEmulator, IotHubClientProtocol.MQTT);
deviceClient.open();
Message messageToSendFromDeviceToHub = new Message("Whatever message you would like to send");
System.out.println("Sending message from device to IoT Hub...");
deviceClient.sendEventAsync(messageToSendFromDeviceToHub, new IotHubEventCallbackImpl(), null);
} catch (IOException e) {
System.out.println("Device client threw an exception: " + e.getMessage());
if (deviceClient != null) {
deviceClient.closeNow();
}
}
}
} catch (ProvisioningDeviceClientException | InterruptedException e) {
System.out.println("Provisioning Device Client threw an exception" + e.getMessage());
if (provisioningDeviceClient != null) {
provisioningDeviceClient.closeNow();
}
}
System.out.println("Press any key to exit...");
scanner.nextLine();
if (provisioningDeviceClient != null) {
provisioningDeviceClient.closeNow();
}
if (deviceClient != null) {
deviceClient.closeNow();
}
System.out.println("Shutting down...");
}
use of com.microsoft.azure.sdk.iot.provisioning.device.internal.exceptions.ProvisioningDeviceClientException in project azure-iot-sdk-java by Azure.
the class ProvisioningTask method executeStateMachineForStatus.
private void executeStateMachineForStatus(RegistrationOperationStatusParser registrationOperationStatusParser) throws TimeoutException, InterruptedException, ExecutionException, ProvisioningDeviceClientException, SecurityProviderException {
boolean isContinue = false;
RegistrationOperationStatusParser statusRegistrationOperationStatusParser = registrationOperationStatusParser;
ProvisioningStatus nextStatus = ProvisioningStatus.fromString(registrationOperationStatusParser.getStatus());
log.info("Current provisioning status: {}", nextStatus);
// continue invoking for status until a terminal state is reached
do {
if (nextStatus == null) {
throw new ProvisioningDeviceClientException("Did not receive a valid status");
}
switch(nextStatus) {
case UNASSIGNED:
// intended fall through
case ASSIGNING:
log.trace("Polling device provisioning service for status of registration...");
statusRegistrationOperationStatusParser = this.invokeStatus(registrationOperationStatusParser.getOperationId());
nextStatus = ProvisioningStatus.fromString(statusRegistrationOperationStatusParser.getStatus());
isContinue = true;
break;
case ASSIGNED:
this.dpsStatus = PROVISIONING_DEVICE_STATUS_ASSIGNED;
DeviceRegistrationResultParser registrationStatus = statusRegistrationOperationStatusParser.getRegistrationState();
if (registrationStatus == null || registrationStatus.getAssignedHub() == null || registrationStatus.getAssignedHub().isEmpty() || registrationStatus.getDeviceId() == null || registrationStatus.getDeviceId().isEmpty()) {
// Codes_SRS_ProvisioningTask_34_018: [Upon reaching the terminal state ASSIGNED, if the registration status json is missing an assigned hub or device id, this function shall throw a ProvisioningDeviceClientException.]
throw new ProvisioningDeviceClientException("Could not retrieve Assigned Hub or Device ID and status changed to Assigned");
}
RegistrationResult registrationInfo = new RegistrationResult(registrationStatus.getAssignedHub(), registrationStatus.getDeviceId(), registrationStatus.getPayload(), PROVISIONING_DEVICE_STATUS_ASSIGNED);
registrationInfo.setRegistrationId(registrationStatus.getRegistrationId());
registrationInfo.setStatus(registrationStatus.getStatus());
registrationInfo.setSubstatus(ProvisioningDeviceClientSubstatus.fromString(registrationStatus.getSubstatus()));
registrationInfo.setCreatedDateTimeUtc(registrationStatus.getCreatedDateTimeUtc());
registrationInfo.setLastUpdatesDateTimeUtc(registrationStatus.getLastUpdatesDateTimeUtc());
registrationInfo.setETag(registrationStatus.getEtag());
if (this.securityProvider instanceof SecurityProviderTpm) {
if (registrationStatus.getTpm() == null || registrationStatus.getTpm().getAuthenticationKey() == null || registrationStatus.getTpm().getAuthenticationKey().isEmpty()) {
// Codes_SRS_ProvisioningTask_34_017: [Upon reaching the terminal state ASSIGNED, if the saved security client is an instance of SecurityClientTpm and if the registration status json does not contain an authentication key, this function shall throw a ProvisioningDeviceClientException.]
throw new ProvisioningDeviceClientException("Could not retrieve Authentication key when status was assigned");
}
// Codes_SRS_ProvisioningTask_34_016: [Upon reaching the terminal state ASSIGNED, if the saved security client is an instance of SecurityClientTpm, the security client shall decrypt and store the authentication key from the statusResponseParser.]
String authenticationKey = registrationStatus.getTpm().getAuthenticationKey();
((SecurityProviderTpm) this.securityProvider).activateIdentityKey(decodeBase64(authenticationKey.getBytes(StandardCharsets.UTF_8)));
}
log.info("Device provisioning service assigned the device successfully");
this.invokeRegistrationCallback(registrationInfo, null);
isContinue = false;
break;
case FAILED:
this.dpsStatus = PROVISIONING_DEVICE_STATUS_FAILED;
String errorMessage = statusRegistrationOperationStatusParser.getRegistrationState().getErrorMessage();
ProvisioningDeviceHubException dpsHubException = new ProvisioningDeviceHubException(errorMessage);
dpsHubException.setErrorCode(registrationOperationStatusParser.getRegistrationState().getErrorCode());
registrationInfo = new RegistrationResult(null, null, null, PROVISIONING_DEVICE_STATUS_FAILED);
log.error("Device provisioning service failed to provision the device, finished with status FAILED: {}", errorMessage);
this.invokeRegistrationCallback(registrationInfo, dpsHubException);
isContinue = false;
break;
case DISABLED:
this.dpsStatus = PROVISIONING_DEVICE_STATUS_DISABLED;
String disabledErrorMessage = statusRegistrationOperationStatusParser.getRegistrationState().getErrorMessage();
dpsHubException = new ProvisioningDeviceHubException(disabledErrorMessage);
dpsHubException.setErrorCode(registrationOperationStatusParser.getRegistrationState().getErrorCode());
registrationInfo = new RegistrationResult(null, null, null, PROVISIONING_DEVICE_STATUS_DISABLED);
log.error("Device provisioning service failed to provision the device, finished with status DISABLED: {}", disabledErrorMessage);
this.invokeRegistrationCallback(registrationInfo, dpsHubException);
isContinue = false;
break;
}
} while (isContinue);
}
use of com.microsoft.azure.sdk.iot.provisioning.device.internal.exceptions.ProvisioningDeviceClientException in project azure-iot-sdk-java by Azure.
the class RegisterTask method authenticateWithSasToken.
private RegistrationOperationStatusParser authenticateWithSasToken(RequestData requestData) throws IOException, InterruptedException, ProvisioningDeviceClientException, SecurityProviderException {
/*SRS_RegisterTask_25_014: [ If the provided security client is for Key then, this method shall construct SasToken by doing the following
1. Build a tokenScope of format <scope>/registrations/<registrationId>
2. Sign the HSM with the string of format <tokenScope>/n<expiryTime> and receive a token
3. Encode the token to Base64 format and UrlEncode it to generate the signature. ]*/
String sasToken = this.constructSasToken();
requestData.setSasToken(sasToken);
// SRS_RegisterTask_25_016: [ If the provided security client is for Key then, this method shall trigger authenticateWithProvisioningService on the contract API using the sasToken generated and wait for response and return it. ]
ResponseData responseDataForSasTokenAuth = new ResponseData();
this.provisioningDeviceClientContract.authenticateWithProvisioningService(requestData, responseCallback, responseDataForSasTokenAuth);
waitForResponse(responseDataForSasTokenAuth);
if (responseDataForSasTokenAuth.getResponseData() != null && responseDataForSasTokenAuth.getContractState() == DPS_REGISTRATION_RECEIVED) {
this.authorization.setSasToken(sasToken);
String jsonBody = new String(responseDataForSasTokenAuth.getResponseData(), StandardCharsets.UTF_8);
try {
return RegistrationOperationStatusParser.createFromJson(jsonBody);
} catch (IllegalArgumentException e) {
ProvisioningErrorParser provisioningErrorParser = ProvisioningErrorParser.createFromJson(jsonBody);
throw new ProvisioningDeviceClientException(provisioningErrorParser.getExceptionMessage());
}
} else {
// SRS_RegisterTask_25_017: [ If the provided security client is for Key then, this method shall throw ProvisioningDeviceClientException if null response to authenticateWithProvisioningService is received. ]
throw new ProvisioningDeviceClientAuthenticationException("Service did not authorize SasToken");
}
}
use of com.microsoft.azure.sdk.iot.provisioning.device.internal.exceptions.ProvisioningDeviceClientException in project azure-iot-sdk-java by Azure.
the class RegisterTask method authenticateWithDPS.
private RegistrationOperationStatusParser authenticateWithDPS() throws ProvisioningDeviceClientException, SecurityProviderException {
if (securityProvider.getRegistrationId() == null) {
throw new ProvisioningDeviceClientException(new IllegalArgumentException("registration id cannot be null"));
}
try {
SSLContext sslContext = securityProvider.getSSLContext();
if (sslContext == null) {
throw new ProvisioningDeviceSecurityException("Null SSL Context received from security client");
}
authorization.setSslContext(sslContext);
if (this.securityProvider instanceof SecurityProviderX509) {
RequestData requestData = new RequestData(securityProvider.getRegistrationId(), sslContext, true, this.provisioningDeviceClientConfig.getPayload());
log.info("Authenticating with device provisioning service using x509 certificates");
return this.authenticateWithX509(requestData);
} else if (this.securityProvider instanceof SecurityProviderTpm) {
SecurityProviderTpm securityProviderTpm = (SecurityProviderTpm) securityProvider;
if (securityProviderTpm.getEndorsementKey() == null || securityProviderTpm.getStorageRootKey() == null) {
throw new ProvisioningDeviceSecurityException(new IllegalArgumentException("Ek or SRK cannot be null"));
}
// SRS_RegisterTask_25_009: [ If the provided security client is for Key then, this method shall save the SSL context to Authorization if it is not null and throw ProvisioningDeviceClientException otherwise. ]
RequestData requestData = new RequestData(securityProviderTpm.getEndorsementKey(), securityProviderTpm.getStorageRootKey(), securityProvider.getRegistrationId(), sslContext, null, this.provisioningDeviceClientConfig.getPayload());
log.info("Authenticating with device provisioning service using tpm");
return this.authenticateWithTPM(requestData);
} else if (this.securityProvider instanceof SecurityProviderSymmetricKey) {
RequestData requestData = new RequestData(securityProvider.getRegistrationId(), sslContext, null, this.provisioningDeviceClientConfig.getPayload());
log.info("Authenticating with device provisioning service using symmetric key");
return this.authenticateWithSasToken(requestData);
} else {
throw new ProvisioningDeviceSecurityException("Unknown Security client received");
}
} catch (SecurityProviderException | IOException | InterruptedException e) {
throw new ProvisioningDeviceSecurityException(e);
}
}
Aggregations