├── .gitignore ├── .travis.yml ├── NOTICE ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── .github ├── dependabot.yml └── PULL_REQUEST_TEMPLATE.md ├── src ├── main │ └── java │ │ └── com │ │ └── awslabs │ │ └── aws │ │ └── iot │ │ └── websockets │ │ ├── data │ │ ├── PolicyEffect.java │ │ ├── ClientId.java │ │ ├── NoToString.java │ │ ├── PolicyResource.java │ │ ├── RoleToAssume.java │ │ ├── EndpointAddress.java │ │ ├── PolicyAction.java │ │ ├── UsernamePassword.java │ │ ├── MqttClientConfig.java │ │ ├── MqttOverWebsocketsUriConfig.java │ │ ├── ScopeDownPolicyStatement.java │ │ └── ScopeDownPolicy.java │ │ ├── MqttOverWebsocketsProvider.java │ │ └── BasicMqttOverWebsocketsProvider.java └── test │ └── java │ └── com │ └── awslabs │ └── aws │ └── iot │ └── websockets │ └── BasicMqttOverWebsocketsProviderTest.java ├── CODE_OF_CONDUCT.md ├── README.md ├── gradlew.bat ├── CONTRIBUTING.md ├── gradlew └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | .gradle 3 | build 4 | out 5 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | script: 2 | - ./gradlew build -xtest 3 | -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | AWS Iot Core Websockets 2 | Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/awslabs/aws-iot-core-websockets/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: gradle 4 | directory: "/" 5 | schedule: 6 | interval: daily 7 | open-pull-requests-limit: 10 8 | -------------------------------------------------------------------------------- /src/main/java/com/awslabs/aws/iot/websockets/data/PolicyEffect.java: -------------------------------------------------------------------------------- 1 | package com.awslabs.aws.iot.websockets.data; 2 | 3 | public enum PolicyEffect { 4 | Allow, 5 | Deny 6 | } 7 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | *Issue #, if available:* 2 | 3 | *Description of changes:* 4 | 5 | 6 | By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice. 7 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.2-all.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | ## Code of Conduct 2 | This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct). 3 | For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact 4 | opensource-codeofconduct@amazon.com with any additional questions or comments. 5 | -------------------------------------------------------------------------------- /src/main/java/com/awslabs/aws/iot/websockets/data/ClientId.java: -------------------------------------------------------------------------------- 1 | package com.awslabs.aws.iot.websockets.data; 2 | 3 | import org.immutables.gson.Gson; 4 | import org.immutables.value.Value; 5 | 6 | @Gson.TypeAdapters 7 | @Value.Immutable 8 | public abstract class ClientId extends NoToString { 9 | public abstract String getClientId(); 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/com/awslabs/aws/iot/websockets/data/NoToString.java: -------------------------------------------------------------------------------- 1 | package com.awslabs.aws.iot.websockets.data; 2 | 3 | public class NoToString { 4 | @Override 5 | public final String toString() { 6 | // This is to make sure string concatenation with this type throws an exception immediately 7 | throw new RuntimeException("This object does not support toString()"); 8 | } 9 | } -------------------------------------------------------------------------------- /src/main/java/com/awslabs/aws/iot/websockets/data/PolicyResource.java: -------------------------------------------------------------------------------- 1 | package com.awslabs.aws.iot.websockets.data; 2 | 3 | public class PolicyResource { 4 | private final String resource; 5 | 6 | public PolicyResource(String resource) { 7 | this.resource = resource; 8 | } 9 | 10 | @Override 11 | public String toString() { 12 | return resource; 13 | } 14 | } 15 | 16 | -------------------------------------------------------------------------------- /src/main/java/com/awslabs/aws/iot/websockets/data/RoleToAssume.java: -------------------------------------------------------------------------------- 1 | package com.awslabs.aws.iot.websockets.data; 2 | 3 | import org.immutables.gson.Gson; 4 | import org.immutables.value.Value; 5 | 6 | import java.util.Optional; 7 | 8 | @Gson.TypeAdapters 9 | @Value.Immutable 10 | public abstract class RoleToAssume extends NoToString { 11 | public abstract Optional getRoleToAssume(); 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/awslabs/aws/iot/websockets/data/EndpointAddress.java: -------------------------------------------------------------------------------- 1 | package com.awslabs.aws.iot.websockets.data; 2 | 3 | import org.immutables.gson.Gson; 4 | import org.immutables.value.Value; 5 | 6 | import java.util.Optional; 7 | 8 | @Gson.TypeAdapters 9 | @Value.Immutable 10 | public abstract class EndpointAddress extends NoToString { 11 | public abstract Optional getEndpointAddress(); 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/awslabs/aws/iot/websockets/data/PolicyAction.java: -------------------------------------------------------------------------------- 1 | package com.awslabs.aws.iot.websockets.data; 2 | 3 | import org.immutables.gson.Gson; 4 | import org.immutables.value.Value; 5 | 6 | public class PolicyAction { 7 | private final String action; 8 | 9 | public PolicyAction(String action) { 10 | this.action = action; 11 | } 12 | 13 | @Override 14 | public String toString() { 15 | return action; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/com/awslabs/aws/iot/websockets/data/UsernamePassword.java: -------------------------------------------------------------------------------- 1 | package com.awslabs.aws.iot.websockets.data; 2 | 3 | import org.immutables.gson.Gson; 4 | import org.immutables.value.Value; 5 | 6 | import java.util.Optional; 7 | 8 | @Gson.TypeAdapters 9 | @Value.Immutable 10 | public abstract class UsernamePassword extends NoToString { 11 | public abstract Optional getUsername(); 12 | 13 | public abstract Optional getPassword(); 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/awslabs/aws/iot/websockets/data/MqttClientConfig.java: -------------------------------------------------------------------------------- 1 | package com.awslabs.aws.iot.websockets.data; 2 | 3 | import org.immutables.gson.Gson; 4 | import org.immutables.value.Value; 5 | import software.amazon.awssdk.regions.Region; 6 | 7 | import java.util.Optional; 8 | 9 | @Gson.TypeAdapters 10 | @Value.Immutable 11 | public abstract class MqttClientConfig extends NoToString { 12 | public abstract ClientId getClientId(); 13 | 14 | public abstract Optional getOptionalMqttOverWebsocketsUriConfig(); 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/awslabs/aws/iot/websockets/data/MqttOverWebsocketsUriConfig.java: -------------------------------------------------------------------------------- 1 | package com.awslabs.aws.iot.websockets.data; 2 | 3 | import org.immutables.gson.Gson; 4 | import org.immutables.value.Value; 5 | import software.amazon.awssdk.auth.credentials.AwsCredentialsProviderChain; 6 | import software.amazon.awssdk.regions.Region; 7 | 8 | import java.util.Optional; 9 | 10 | @Gson.TypeAdapters 11 | @Value.Immutable 12 | public abstract class MqttOverWebsocketsUriConfig extends NoToString { 13 | public abstract Optional optionalAwsCredentialsProviderChain(); 14 | 15 | public abstract Optional optionalRegion(); 16 | 17 | public abstract Optional optionalEndpointAddress(); 18 | 19 | public abstract Optional optionalRoleToAssume(); 20 | 21 | public abstract Optional optionalScopeDownPolicy(); 22 | 23 | public abstract Optional optionalScopeDownPolicyJson(); 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/awslabs/aws/iot/websockets/data/ScopeDownPolicyStatement.java: -------------------------------------------------------------------------------- 1 | package com.awslabs.aws.iot.websockets.data; 2 | 3 | import com.google.gson.Gson; 4 | 5 | import java.util.HashMap; 6 | import java.util.List; 7 | import java.util.Map; 8 | import java.util.stream.Collectors; 9 | 10 | public class ScopeDownPolicyStatement { 11 | private final PolicyEffect effect; 12 | 13 | private final List action; 14 | 15 | private final List resource; 16 | 17 | public ScopeDownPolicyStatement(PolicyEffect effect, List action, List resource) { 18 | this.effect = effect; 19 | this.action = action; 20 | this.resource = resource; 21 | } 22 | 23 | public PolicyEffect getEffect() { 24 | return effect; 25 | } 26 | 27 | public List getAction() { 28 | return action; 29 | } 30 | 31 | public List getResource() { 32 | return resource; 33 | } 34 | 35 | public Map toMap() { 36 | Map map = new HashMap<>(); 37 | List actions = action.stream().map(PolicyAction::toString).collect(Collectors.toList()); 38 | List resources = resource.stream().map(PolicyResource::toString).collect(Collectors.toList()); 39 | 40 | map.put("Effect", effect.toString()); 41 | map.put("Action", actions); 42 | map.put("Resource", resources); 43 | 44 | return map; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/com/awslabs/aws/iot/websockets/data/ScopeDownPolicy.java: -------------------------------------------------------------------------------- 1 | package com.awslabs.aws.iot.websockets.data; 2 | 3 | import com.google.gson.Gson; 4 | 5 | import java.util.HashMap; 6 | import java.util.List; 7 | import java.util.Map; 8 | import java.util.stream.Collectors; 9 | 10 | public class ScopeDownPolicy { 11 | private final String version; 12 | private final List scopeDownPolicyStatements; 13 | 14 | public ScopeDownPolicy(String version, List scopeDownPolicyStatements) { 15 | this.version = version; 16 | this.scopeDownPolicyStatements = scopeDownPolicyStatements; 17 | } 18 | 19 | public ScopeDownPolicy(List scopeDownPolicyStatements) { 20 | this.version = getDefaultVersion(); 21 | this.scopeDownPolicyStatements = scopeDownPolicyStatements; 22 | } 23 | 24 | public String getDefaultVersion() { 25 | return "2012-10-17"; 26 | } 27 | 28 | public String getVersion() { 29 | return version; 30 | } 31 | 32 | public List getScopeDownPolicyStatements() { 33 | return scopeDownPolicyStatements; 34 | } 35 | 36 | @Override 37 | public String toString() { 38 | Map map = new HashMap<>(); 39 | List statement = scopeDownPolicyStatements.stream().map(ScopeDownPolicyStatement::toMap).collect(Collectors.toList()); 40 | 41 | map.put("Version", version); 42 | map.put("Statement", statement); 43 | 44 | return new Gson().toJson(map); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/com/awslabs/aws/iot/websockets/MqttOverWebsocketsProvider.java: -------------------------------------------------------------------------------- 1 | package com.awslabs.aws.iot.websockets; 2 | 3 | import com.awslabs.aws.iot.websockets.data.ImmutableUsernamePassword; 4 | import com.awslabs.aws.iot.websockets.data.MqttClientConfig; 5 | import com.awslabs.aws.iot.websockets.data.MqttOverWebsocketsUriConfig; 6 | import org.eclipse.paho.client.mqttv3.*; 7 | 8 | import java.io.UnsupportedEncodingException; 9 | import java.security.InvalidKeyException; 10 | import java.security.NoSuchAlgorithmException; 11 | import java.util.Optional; 12 | 13 | public interface MqttOverWebsocketsProvider { 14 | MqttClient getMqttClient(MqttClientConfig mqttClientConfig) throws MqttException, NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException; 15 | 16 | MqttAsyncClient getMqttAsyncClient(MqttClientConfig mqttClientConfig) throws MqttException, NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException; 17 | 18 | /** 19 | * Connects a synchronous MQTT client. Does nothing if it is already connected. 20 | * 21 | * @param mqttClient 22 | * @throws MqttException 23 | */ 24 | void connect(MqttClient mqttClient) throws MqttException; 25 | 26 | /** 27 | * Connects a synchronous MQTT client. Does nothing if it is already connected. 28 | * 29 | * @param mqttClient 30 | * @param usernamePassword 31 | * @throws MqttException 32 | */ 33 | void connect(MqttClient mqttClient, ImmutableUsernamePassword usernamePassword) throws MqttException; 34 | 35 | /** 36 | * Connects an asynchronous MQTT client 37 | * 38 | * @param mqttAsyncClient 39 | * @return Optional.empty() if already connected, otherwise an Optional of the MqttToken 40 | * @throws MqttException 41 | */ 42 | Optional connect(MqttAsyncClient mqttAsyncClient) throws MqttException; 43 | 44 | /** 45 | * Connects an asynchronous MQTT client 46 | * 47 | * @param mqttAsyncClient 48 | * @param usernamePassword 49 | * @param userContext 50 | * @param callback 51 | * @return Optional.empty() if already connected, otherwise an Optional of the MqttToken 52 | * @throws MqttException 53 | */ 54 | Optional connect(MqttAsyncClient mqttAsyncClient, ImmutableUsernamePassword usernamePassword, Object userContext, IMqttActionListener callback) throws MqttException; 55 | 56 | // Derived from: http://docs.aws.amazon.com/iot/latest/developerguide/iot-dg.pdf 57 | String getMqttOverWebsocketsUriString(Optional optionalMqttOverWebsocketsUriConfig) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException; 58 | } 59 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## AWS IoT Core Websockets 2 | 3 | [![Build Status](https://travis-ci.org/awslabs/aws-iot-core-websockets.svg?branch=master)](https://travis-ci.org/awslabs/aws-iot-core-websockets) 4 | [![Open Issues](https://img.shields.io/github/issues-raw/awslabs/aws-iot-core-websockets.svg)](https://github.com/awslabs/aws-iot-core-websockets/issues) 5 | [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://github.com/awslabs/aws-iot-core-websockets/blob/master/LICENSE) 6 | 7 | A library that handles connecting third-party websockets based MQTT clients to AWS IoT Core. 8 | 9 | ## Why MQTT over WebSockets? 10 | 11 | MQTT over WebSockets allows you to use SigV4 credentials. This means that you can use this library to connect to AWS IoT Core, 12 | without certificates, assuming that you have a way to get SigV4 credentials. For normal IAM users this can be from 13 | `.aws/config`'s access key and secret key ID, or it could be from the EC2 instance meta-data service so you can use an 14 | instance profile, or it could be from the [AWS Secure Token Service](https://docs.aws.amazon.com/STS/latest/APIReference/Welcome.html) 15 | so you can ship temporary credentials to other systems over any secure delivery mechanism that you have set up already. 16 | 17 | ## Can I use SigV4 credentials with normal MQTT? 18 | 19 | [Not as of 2021-05-04 according to the AWS IoT documentation](https://docs.aws.amazon.com/iot/latest/developerguide/protocols.html). 20 | 21 | ## How do I include it in my Gradle project? 22 | 23 | 1. Add the jitpack repo to the repositories section 24 | 25 | ``` 26 | maven { url 'https://jitpack.io' } 27 | ``` 28 | 29 | 2. Add the dependency version [(replace x.y.z with the appropriate version from the JitPack site)](https://jitpack.io/#awslabs/aws-iot-core-websockets) 30 | 31 | ``` 32 | def awsIotCoreWebsocketsVersion = 'x.y.z' 33 | ``` 34 | 35 | 3. Add the dependency to the dependencies section 36 | 37 | ``` 38 | compile "com.github.awslabs:aws-iot-core-websockets:$awsIotCoreWebsocketsVersion" 39 | ``` 40 | 41 | ## How do I use it? 42 | 43 | Check out an [example in the IoT reference architectures repo](https://github.com/aws-samples/iot-reference-architectures/tree/master/mqtt-over-websockets-jitpack). 44 | 45 | ## Is there a really simple example snippet to get me started? 46 | 47 | Of course, all you have to do after including the library to get an MQTT client with your IAM credentials is this: 48 | 49 | ``` 50 | mqttOverWebsocketsProvider = new BasicMqttOverWebsocketsProvider(); 51 | String uuid = UUID.randomUUID().toString(); 52 | clientId = ImmutableClientId.builder().clientId(uuid).build(); 53 | mqttClient = mqttOverWebsocketsProvider.getMqttClient(clientId); 54 | ``` 55 | 56 | ## License 57 | 58 | This library is licensed under the Apache 2.0 License. 59 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing Guidelines 2 | 3 | Thank you for your interest in contributing to our project. Whether it's a bug report, new feature, correction, or additional 4 | documentation, we greatly value feedback and contributions from our community. 5 | 6 | Please read through this document before submitting any issues or pull requests to ensure we have all the necessary 7 | information to effectively respond to your bug report or contribution. 8 | 9 | 10 | ## Reporting Bugs/Feature Requests 11 | 12 | We welcome you to use the GitHub issue tracker to report bugs or suggest features. 13 | 14 | When filing an issue, please check [existing open](https://github.com/awslabs/aws-iot-core-websockets/issues), or [recently closed](https://github.com/awslabs/aws-iot-core-websockets/issues?utf8=%E2%9C%93&q=is%3Aissue%20is%3Aclosed%20), issues to make sure somebody else hasn't already 15 | reported the issue. Please try to include as much information as you can. Details like these are incredibly useful: 16 | 17 | * A reproducible test case or series of steps 18 | * The version of our code being used 19 | * Any modifications you've made relevant to the bug 20 | * Anything unusual about your environment or deployment 21 | 22 | 23 | ## Contributing via Pull Requests 24 | Contributions via pull requests are much appreciated. Before sending us a pull request, please ensure that: 25 | 26 | 1. You are working against the latest source on the *master* branch. 27 | 2. You check existing open, and recently merged, pull requests to make sure someone else hasn't addressed the problem already. 28 | 3. You open an issue to discuss any significant work - we would hate for your time to be wasted. 29 | 30 | To send us a pull request, please: 31 | 32 | 1. Fork the repository. 33 | 2. Modify the source; please focus on the specific change you are contributing. If you also reformat all the code, it will be hard for us to focus on your change. 34 | 3. Ensure local tests pass. 35 | 4. Commit to your fork using clear commit messages. 36 | 5. Send us a pull request, answering any default questions in the pull request interface. 37 | 6. Pay attention to any automated CI failures reported in the pull request, and stay involved in the conversation. 38 | 39 | GitHub provides additional document on [forking a repository](https://help.github.com/articles/fork-a-repo/) and 40 | [creating a pull request](https://help.github.com/articles/creating-a-pull-request/). 41 | 42 | 43 | ## Finding contributions to work on 44 | Looking at the existing issues is a great way to find something to contribute on. As our projects, by default, use the default GitHub issue labels (enhancement/bug/duplicate/help wanted/invalid/question/wontfix), looking at any ['help wanted'](https://github.com/awslabs/aws-iot-core-websockets/labels/help%20wanted) issues is a great place to start. 45 | 46 | 47 | ## Code of Conduct 48 | This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct). 49 | For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact 50 | opensource-codeofconduct@amazon.com with any additional questions or comments. 51 | 52 | 53 | ## Security issue notifications 54 | If you discover a potential security issue in this project we ask that you notify AWS/Amazon Security via our [vulnerability reporting page](http://aws.amazon.com/security/vulnerability-reporting/). Please do **not** create a public github issue. 55 | 56 | 57 | ## Licensing 58 | 59 | See the [LICENSE](https://github.com/awslabs/aws-iot-core-websockets/blob/master/LICENSE) file for our project's licensing. We will ask you to confirm the licensing of your contribution. 60 | 61 | We may ask you to sign a [Contributor License Agreement (CLA)](http://en.wikipedia.org/wiki/Contributor_License_Agreement) for larger changes. 62 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit 84 | 85 | APP_NAME="Gradle" 86 | APP_BASE_NAME=${0##*/} 87 | 88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | 142 | # Increase the maximum file descriptors if we can. 143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 144 | case $MAX_FD in #( 145 | max*) 146 | MAX_FD=$( ulimit -H -n ) || 147 | warn "Could not query maximum file descriptor limit" 148 | esac 149 | case $MAX_FD in #( 150 | '' | soft) :;; #( 151 | *) 152 | ulimit -n "$MAX_FD" || 153 | warn "Could not set maximum file descriptor limit to $MAX_FD" 154 | esac 155 | fi 156 | 157 | # Collect all arguments for the java command, stacking in reverse order: 158 | # * args from the command line 159 | # * the main class name 160 | # * -classpath 161 | # * -D...appname settings 162 | # * --module-path (only if needed) 163 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 164 | 165 | # For Cygwin or MSYS, switch paths to Windows format before running java 166 | if "$cygwin" || "$msys" ; then 167 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 168 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 169 | 170 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 171 | 172 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 173 | for arg do 174 | if 175 | case $arg in #( 176 | -*) false ;; # don't mess with options #( 177 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 178 | [ -e "$t" ] ;; #( 179 | *) false ;; 180 | esac 181 | then 182 | arg=$( cygpath --path --ignore --mixed "$arg" ) 183 | fi 184 | # Roll the args list around exactly as many times as the number of 185 | # args, so each arg winds up back in the position where it started, but 186 | # possibly modified. 187 | # 188 | # NB: a `for` loop captures its iteration list before it begins, so 189 | # changing the positional parameters here affects neither the number of 190 | # iterations, nor the values presented in `arg`. 191 | shift # remove old arg 192 | set -- "$@" "$arg" # push replacement arg 193 | done 194 | fi 195 | 196 | # Collect all arguments for the java command; 197 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 198 | # shell script including quotes and variable substitutions, so put them in 199 | # double quotes to make sure that they get re-expanded; and 200 | # * put everything else in single quotes, so that it's not re-expanded. 201 | 202 | set -- \ 203 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 204 | -classpath "$CLASSPATH" \ 205 | org.gradle.wrapper.GradleWrapperMain \ 206 | "$@" 207 | 208 | # Use "xargs" to parse quoted args. 209 | # 210 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 211 | # 212 | # In Bash we could simply go: 213 | # 214 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 215 | # set -- "${ARGS[@]}" "$@" 216 | # 217 | # but POSIX shell has neither arrays nor command substitution, so instead we 218 | # post-process each arg (as a line of input to sed) to backslash-escape any 219 | # character that might be a shell metacharacter, then use eval to reverse 220 | # that process (while maintaining the separation between arguments), and wrap 221 | # the whole thing up as a single "set" statement. 222 | # 223 | # This will of course break if any of these variables contains a newline or 224 | # an unmatched quote. 225 | # 226 | 227 | eval "set -- $( 228 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 229 | xargs -n1 | 230 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 231 | tr '\n' ' ' 232 | )" '"$@"' 233 | 234 | exec "$JAVACMD" "$@" 235 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | -------------------------------------------------------------------------------- /src/test/java/com/awslabs/aws/iot/websockets/BasicMqttOverWebsocketsProviderTest.java: -------------------------------------------------------------------------------- 1 | package com.awslabs.aws.iot.websockets; 2 | 3 | import com.awslabs.aws.iot.websockets.data.*; 4 | import org.eclipse.paho.client.mqttv3.MqttClient; 5 | import org.eclipse.paho.client.mqttv3.MqttException; 6 | import org.eclipse.paho.client.mqttv3.MqttMessage; 7 | import org.jetbrains.annotations.NotNull; 8 | import org.junit.Before; 9 | import org.junit.Test; 10 | import software.amazon.awssdk.auth.credentials.AwsCredentials; 11 | import software.amazon.awssdk.auth.credentials.AwsCredentialsProviderChain; 12 | import software.amazon.awssdk.auth.credentials.AwsSessionCredentials; 13 | import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; 14 | import software.amazon.awssdk.regions.Region; 15 | import software.amazon.awssdk.regions.providers.DefaultAwsRegionProviderChain; 16 | import software.amazon.awssdk.services.sts.StsClient; 17 | import software.amazon.awssdk.services.sts.model.Credentials; 18 | import software.amazon.awssdk.services.sts.model.GetFederationTokenRequest; 19 | import software.amazon.awssdk.services.sts.model.GetFederationTokenResponse; 20 | import software.amazon.awssdk.services.sts.model.PolicyDescriptorType; 21 | 22 | import java.io.EOFException; 23 | import java.io.UnsupportedEncodingException; 24 | import java.security.InvalidKeyException; 25 | import java.security.NoSuchAlgorithmException; 26 | import java.util.Arrays; 27 | import java.util.Optional; 28 | import java.util.UUID; 29 | 30 | import static org.hamcrest.CoreMatchers.*; 31 | import static org.hamcrest.MatcherAssert.assertThat; 32 | import static org.junit.Assert.assertThrows; 33 | 34 | public class BasicMqttOverWebsocketsProviderTest { 35 | private BasicMqttOverWebsocketsProvider basicMqttOverWebsocketsProvider; 36 | private ImmutableClientId clientId; 37 | private Region region; 38 | private ScopeDownPolicy goodConnectScopeDownPolicy; 39 | private ScopeDownPolicy badConnectScopeDownPolicy; 40 | private ScopeDownPolicy goodConnectAndPublishScopeDownPolicy; 41 | private ImmutableEndpointAddress emptyEndpoint; 42 | private ImmutableRoleToAssume emptyRoleToAssume; 43 | private StaticCredentialsProvider staticCredentialsProvider; 44 | 45 | @Before 46 | public void setup() { 47 | StsClient stsClient = StsClient.create(); 48 | PolicyDescriptorType policyDescriptorType = PolicyDescriptorType.builder() 49 | .arn("arn:aws:iam::aws:policy/AdministratorAccess") 50 | .build(); 51 | GetFederationTokenRequest getFederationTokenRequest = GetFederationTokenRequest.builder() 52 | .name("temp") 53 | .policyArns(policyDescriptorType) 54 | .build(); 55 | GetFederationTokenResponse stsCredentials = stsClient.getFederationToken(getFederationTokenRequest); 56 | Credentials credentials = stsCredentials.credentials(); 57 | AwsCredentials awsCredentials = AwsSessionCredentials.create(credentials.accessKeyId(), credentials.secretAccessKey(), credentials.sessionToken()); 58 | staticCredentialsProvider = StaticCredentialsProvider.create(awsCredentials); 59 | region = new DefaultAwsRegionProviderChain().getRegion(); 60 | basicMqttOverWebsocketsProvider = new BasicMqttOverWebsocketsProvider(); 61 | String accountId = basicMqttOverWebsocketsProvider.getAccountId.apply(stsClient); 62 | clientId = ImmutableClientId.builder().clientId(UUID.randomUUID().toString()).build(); 63 | 64 | String goodClientIdArn = String.join("", "arn:aws:iot:", region.id(), ":", accountId, ":client/", clientId.getClientId()); 65 | String badClientIdArn = String.join("", goodClientIdArn, "xxx"); 66 | String publishAnywhereArn = String.join("", "arn:aws:iot:", region.id(), ":", accountId, ":topic/", "*"); 67 | 68 | PolicyAction connectAction = new PolicyAction("iot:Connect"); 69 | PolicyAction publishAction = new PolicyAction("iot:Publish"); 70 | 71 | PolicyResource goodClientIdResource = new PolicyResource(goodClientIdArn); 72 | PolicyResource badClientIdResource = new PolicyResource(badClientIdArn); 73 | PolicyResource publishAnywhereResource = new PolicyResource(publishAnywhereArn); 74 | 75 | ScopeDownPolicyStatement goodConnectScopeDownPolicyStatement = new ScopeDownPolicyStatement(PolicyEffect.Allow, Arrays.asList(connectAction), Arrays.asList(goodClientIdResource)); 76 | ScopeDownPolicyStatement badConnectScopeDownPolicyStatement = new ScopeDownPolicyStatement(PolicyEffect.Allow, Arrays.asList(connectAction), Arrays.asList(badClientIdResource)); 77 | ScopeDownPolicyStatement publishAnywhereScopeDownPolicyStatement = new ScopeDownPolicyStatement(PolicyEffect.Allow, Arrays.asList(publishAction), Arrays.asList(publishAnywhereResource)); 78 | 79 | goodConnectScopeDownPolicy = new ScopeDownPolicy(Arrays.asList(goodConnectScopeDownPolicyStatement)); 80 | badConnectScopeDownPolicy = new ScopeDownPolicy(Arrays.asList(badConnectScopeDownPolicyStatement)); 81 | goodConnectAndPublishScopeDownPolicy = new ScopeDownPolicy(Arrays.asList(goodConnectScopeDownPolicyStatement, publishAnywhereScopeDownPolicyStatement)); 82 | 83 | emptyEndpoint = ImmutableEndpointAddress.builder().build(); 84 | emptyRoleToAssume = ImmutableRoleToAssume.builder().build(); 85 | } 86 | 87 | @Test 88 | public void shouldGetAClientAndConnect() throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException, MqttException { 89 | MqttClientConfig mqttClientConfig = ImmutableMqttClientConfig.builder().clientId(clientId).build(); 90 | MqttClient mqttClient = basicMqttOverWebsocketsProvider.getMqttClient(mqttClientConfig); 91 | basicMqttOverWebsocketsProvider.connect(mqttClient); 92 | } 93 | 94 | @Test 95 | public void shouldGetAClientAndConnectWithScopeDownPolicy() throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException, MqttException { 96 | MqttClientConfig mqttClientConfig = getMqttClientConfigWithScopeDown(goodConnectScopeDownPolicy); 97 | MqttClient mqttClient = basicMqttOverWebsocketsProvider.getMqttClient(mqttClientConfig); 98 | basicMqttOverWebsocketsProvider.connect(mqttClient); 99 | } 100 | 101 | @Test 102 | public void shouldGetAClientAndFailToConnectWithScopeDownPolicy() throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException, MqttException { 103 | MqttClientConfig mqttClientConfig = getMqttClientConfigWithScopeDown(badConnectScopeDownPolicy); 104 | MqttClient mqttClient = basicMqttOverWebsocketsProvider.getMqttClient(mqttClientConfig); 105 | MqttException mqttException = assertThrows(MqttException.class, () -> basicMqttOverWebsocketsProvider.connect(mqttClient)); 106 | assertThat(mqttException.getCause().getMessage(), containsString("Already connected")); 107 | } 108 | 109 | @Test 110 | public void shouldPublishAMessageWithAPermissivePolicy() throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException, MqttException { 111 | MqttClientConfig mqttClientConfig = getMqttClientConfigWithScopeDown(goodConnectAndPublishScopeDownPolicy); 112 | MqttClient mqttClient = basicMqttOverWebsocketsProvider.getMqttClient(mqttClientConfig); 113 | basicMqttOverWebsocketsProvider.connect(mqttClient); 114 | 115 | String topic = "test"; 116 | MqttMessage mqttMessage = new MqttMessage("testing".getBytes()); 117 | mqttClient.publish(topic, mqttMessage); 118 | } 119 | 120 | @Test 121 | public void shouldPublishWithPermissiveTemporaryCredentials() throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException, MqttException { 122 | MqttClientConfig mqttClientConfig = getMqttClientConfigWithoutScopeDown(); 123 | MqttClient mqttClient = basicMqttOverWebsocketsProvider.getMqttClient(mqttClientConfig); 124 | basicMqttOverWebsocketsProvider.connect(mqttClient); 125 | 126 | String topic = "test"; 127 | MqttMessage mqttMessage = new MqttMessage("testing".getBytes()); 128 | mqttClient.publish(topic, mqttMessage); 129 | } 130 | 131 | @Test 132 | public void shouldNotPublishAMessageWithAConnectOnlyPolicy() throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException, MqttException { 133 | MqttClientConfig mqttClientConfig = getMqttClientConfigWithScopeDown(goodConnectScopeDownPolicy); 134 | MqttClient mqttClient = basicMqttOverWebsocketsProvider.getMqttClient(mqttClientConfig); 135 | basicMqttOverWebsocketsProvider.connect(mqttClient); 136 | 137 | String topic = "test"; 138 | MqttMessage mqttMessage = new MqttMessage("testing".getBytes()); 139 | MqttException mqttException = assertThrows(MqttException.class, () -> mqttClient.publish(topic, mqttMessage)); 140 | assertThat(mqttException.getCause(), is(instanceOf(EOFException.class))); 141 | } 142 | 143 | @Test 144 | public void shouldThrowAnExceptionWithTwoScopeDownPolicies() throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException, MqttException { 145 | MqttOverWebsocketsUriConfig mqttOverWebsocketsUriConfig = ImmutableMqttOverWebsocketsUriConfig.builder() 146 | .optionalScopeDownPolicy(new ScopeDownPolicy("", null)) 147 | .optionalScopeDownPolicyJson("") 148 | .build(); 149 | MqttClientConfig mqttClientConfig = ImmutableMqttClientConfig.builder() 150 | .clientId(clientId) 151 | .optionalMqttOverWebsocketsUriConfig(mqttOverWebsocketsUriConfig) 152 | .build(); 153 | RuntimeException runtimeException = assertThrows(RuntimeException.class, () -> basicMqttOverWebsocketsProvider.getMqttClient(mqttClientConfig)); 154 | assertThat(runtimeException.getMessage(), containsString("but not both")); 155 | } 156 | 157 | @NotNull 158 | private MqttClientConfig getMqttClientConfigWithScopeDown(ScopeDownPolicy scopeDownPolicy) { 159 | MqttOverWebsocketsUriConfig mqttOverWebsocketsUriConfig = ImmutableMqttOverWebsocketsUriConfig.builder() 160 | .optionalScopeDownPolicy(scopeDownPolicy) 161 | .build(); 162 | 163 | return ImmutableMqttClientConfig.builder() 164 | .clientId(clientId) 165 | .optionalMqttOverWebsocketsUriConfig(mqttOverWebsocketsUriConfig) 166 | .build(); 167 | } 168 | 169 | @NotNull 170 | private MqttClientConfig getMqttClientConfigWithoutScopeDown() { 171 | AwsCredentialsProviderChain awsCredentialsProviderChain = AwsCredentialsProviderChain.builder() 172 | .addCredentialsProvider(staticCredentialsProvider) 173 | .build(); 174 | 175 | MqttOverWebsocketsUriConfig mqttOverWebsocketsUriConfig = ImmutableMqttOverWebsocketsUriConfig.builder() 176 | .optionalAwsCredentialsProviderChain(Optional.of(awsCredentialsProviderChain)) 177 | .build(); 178 | 179 | return ImmutableMqttClientConfig.builder() 180 | .clientId(clientId) 181 | .optionalMqttOverWebsocketsUriConfig(mqttOverWebsocketsUriConfig) 182 | .build(); 183 | } 184 | } 185 | -------------------------------------------------------------------------------- /src/main/java/com/awslabs/aws/iot/websockets/BasicMqttOverWebsocketsProvider.java: -------------------------------------------------------------------------------- 1 | package com.awslabs.aws.iot.websockets; 2 | 3 | import com.awslabs.aws.iot.websockets.data.*; 4 | import io.vavr.Function1; 5 | import io.vavr.Function2; 6 | import io.vavr.Tuple; 7 | import io.vavr.Tuple2; 8 | import org.eclipse.paho.client.mqttv3.*; 9 | import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence; 10 | import org.jetbrains.annotations.NotNull; 11 | import org.joda.time.DateTime; 12 | import org.joda.time.DateTimeZone; 13 | import org.joda.time.format.DateTimeFormat; 14 | import org.joda.time.format.DateTimeFormatter; 15 | import org.slf4j.Logger; 16 | import org.slf4j.LoggerFactory; 17 | import software.amazon.awssdk.auth.credentials.*; 18 | import software.amazon.awssdk.http.apache.ApacheHttpClient; 19 | import software.amazon.awssdk.regions.Region; 20 | import software.amazon.awssdk.regions.providers.AwsRegionProviderChain; 21 | import software.amazon.awssdk.regions.providers.DefaultAwsRegionProviderChain; 22 | import software.amazon.awssdk.services.iot.IotClient; 23 | import software.amazon.awssdk.services.iot.IotClientBuilder; 24 | import software.amazon.awssdk.services.iot.model.DescribeEndpointRequest; 25 | import software.amazon.awssdk.services.sts.StsClient; 26 | import software.amazon.awssdk.services.sts.StsClientBuilder; 27 | import software.amazon.awssdk.services.sts.model.*; 28 | 29 | import javax.crypto.Mac; 30 | import javax.crypto.spec.SecretKeySpec; 31 | import javax.inject.Inject; 32 | import java.io.UnsupportedEncodingException; 33 | import java.net.URLEncoder; 34 | import java.nio.charset.StandardCharsets; 35 | import java.security.InvalidKeyException; 36 | import java.security.MessageDigest; 37 | import java.security.NoSuchAlgorithmException; 38 | import java.util.HashMap; 39 | import java.util.Map; 40 | import java.util.Optional; 41 | import java.util.UUID; 42 | 43 | public class BasicMqttOverWebsocketsProvider implements MqttOverWebsocketsProvider { 44 | private static final String ARN_AWS_IAM = "arn:aws:iam::"; 45 | private static final Logger log = LoggerFactory.getLogger(BasicMqttOverWebsocketsProvider.class); 46 | 47 | private static final ApacheHttpClient.Builder apacheClientBuilder = ApacheHttpClient.builder(); 48 | private static final Map, String> endpointMap = new HashMap<>(); 49 | public static final String X_AMZ_SIGNED_HEADERS = "X-Amz-SignedHeaders"; 50 | 51 | // This is not private so that a test can override it if necessary 52 | AwsCredentialsProvider credentialsProvider = DefaultCredentialsProvider.create(); 53 | 54 | @Inject 55 | public BasicMqttOverWebsocketsProvider() { 56 | } 57 | 58 | @Override 59 | public MqttClient getMqttClient(MqttClientConfig mqttClientConfig) throws MqttException, NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException { 60 | String mqttOverWebsocketsUri = getMqttOverWebsocketsUriString(mqttClientConfig.getOptionalMqttOverWebsocketsUriConfig()); 61 | 62 | MemoryPersistence persistence = new MemoryPersistence(); 63 | 64 | return new MqttClient(mqttOverWebsocketsUri, mqttClientConfig.getClientId().getClientId(), persistence); 65 | } 66 | 67 | @Override 68 | public MqttAsyncClient getMqttAsyncClient(MqttClientConfig mqttClientConfig) throws MqttException, NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException { 69 | String mqttOverWebsocketsUri = getMqttOverWebsocketsUriString(mqttClientConfig.getOptionalMqttOverWebsocketsUriConfig()); 70 | 71 | MemoryPersistence persistence = new MemoryPersistence(); 72 | 73 | return new MqttAsyncClient(mqttOverWebsocketsUri, mqttClientConfig.getClientId().getClientId(), persistence); 74 | } 75 | 76 | @Override 77 | public void connect(MqttClient mqttClient) throws MqttException { 78 | MqttConnectOptions connOpts = new MqttConnectOptions(); 79 | connOpts.setCleanSession(true); 80 | mqttClient.connect(connOpts); 81 | } 82 | 83 | @Override 84 | public void connect(MqttClient mqttClient, ImmutableUsernamePassword usernamePassword) throws MqttException { 85 | MqttConnectOptions connOpts = new MqttConnectOptions(); 86 | connOpts.setCleanSession(true); 87 | setUsernamePassword(usernamePassword, connOpts); 88 | mqttClient.connect(connOpts); 89 | } 90 | 91 | private void setUsernamePassword(ImmutableUsernamePassword usernamePassword, MqttConnectOptions connOpts) { 92 | usernamePassword.getUsername().ifPresent(connOpts::setUserName); 93 | usernamePassword.getPassword().ifPresent(connOpts::setPassword); 94 | } 95 | 96 | @Override 97 | public Optional connect(MqttAsyncClient mqttAsyncClient) throws MqttException { 98 | MqttConnectOptions connOpts = new MqttConnectOptions(); 99 | connOpts.setCleanSession(true); 100 | 101 | return Optional.of(mqttAsyncClient.connect(connOpts)); 102 | } 103 | 104 | @Override 105 | public Optional connect(MqttAsyncClient mqttAsyncClient, ImmutableUsernamePassword usernamePassword, Object userContext, IMqttActionListener callback) throws MqttException { 106 | MqttConnectOptions connOpts = new MqttConnectOptions(); 107 | connOpts.setCleanSession(true); 108 | setUsernamePassword(usernamePassword, connOpts); 109 | 110 | return Optional.of(mqttAsyncClient.connect(connOpts, userContext, callback)); 111 | } 112 | 113 | private String getDateStamp(DateTime dateTime) { 114 | DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyyyMMdd"); 115 | return dateTimeFormatter.print(dateTime.withZone(DateTimeZone.UTC)); 116 | } 117 | 118 | private String getAmzDate(DateTime dateTime) { 119 | DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyyyMMdd'T'HHmmss'Z'"); 120 | return dateTimeFormatter.print(dateTime.withZone(DateTimeZone.UTC)); 121 | } 122 | 123 | // Derived from: http://docs.aws.amazon.com/iot/latest/developerguide/iot-dg.pdf 124 | @Override 125 | public String getMqttOverWebsocketsUriString(Optional optionalMqttOverWebsocketsUriConfig) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException { 126 | Optional optionalScopeDownJson = Optional.empty(); 127 | 128 | if (optionalMqttOverWebsocketsUriConfig.isPresent()) { 129 | // We have a websockets config, have they've specified both the policy JSON and the policy object? 130 | MqttOverWebsocketsUriConfig mqttOverWebsocketsUriConfig = optionalMqttOverWebsocketsUriConfig.get(); 131 | if (mqttOverWebsocketsUriConfig.optionalScopeDownPolicy().isPresent() && 132 | mqttOverWebsocketsUriConfig.optionalScopeDownPolicyJson().isPresent()) { 133 | throw new RuntimeException("Scope down policy object and scope down policy JSON can not be used simultaneously. Use either a scope down policy object or scope down policy JSON but not both."); 134 | } 135 | 136 | if (mqttOverWebsocketsUriConfig.optionalScopeDownPolicy().isPresent()) { 137 | optionalScopeDownJson = mqttOverWebsocketsUriConfig.optionalScopeDownPolicy().map(ScopeDownPolicy::toString); 138 | } else if (mqttOverWebsocketsUriConfig.optionalScopeDownPolicyJson().isPresent()) { 139 | optionalScopeDownJson = mqttOverWebsocketsUriConfig.optionalScopeDownPolicyJson(); 140 | } 141 | } 142 | 143 | long time = System.currentTimeMillis(); 144 | DateTime dateTime = new DateTime(time); 145 | String dateStamp = getDateStamp(dateTime); 146 | String amzdate = getAmzDate(dateTime); 147 | String service = "iotdata"; 148 | Optional optionalRegion = optionalMqttOverWebsocketsUriConfig.flatMap(MqttOverWebsocketsUriConfig::optionalRegion); 149 | Optional optionalAwsCredentialsProviderChain = optionalMqttOverWebsocketsUriConfig.flatMap(MqttOverWebsocketsUriConfig::optionalAwsCredentialsProviderChain); 150 | Region region = optionalRegion.orElseGet(this::getDefaultRegionString); 151 | String regionString = region.toString(); 152 | String clientEndpoint = optionalMqttOverWebsocketsUriConfig 153 | .flatMap(MqttOverWebsocketsUriConfig::optionalEndpointAddress) 154 | .flatMap(EndpointAddress::getEndpointAddress) 155 | .orElseGet(() -> getEndpointAddressForRegion(optionalRegion)); 156 | 157 | AwsCredentials awsCredentials; 158 | String awsAccessKeyId; 159 | String awsSecretAccessKey; 160 | Optional optionalSessionToken = Optional.empty(); 161 | 162 | Optional optionalRoleToAssume = optionalMqttOverWebsocketsUriConfig 163 | .flatMap(MqttOverWebsocketsUriConfig::optionalRoleToAssume) 164 | .flatMap(RoleToAssume::getRoleToAssume); 165 | 166 | StsClient stsClient = getStsClient.apply(optionalAwsCredentialsProviderChain, optionalRegion); 167 | 168 | if (!optionalRoleToAssume.isPresent()) { 169 | if (optionalScopeDownJson.isPresent()) { 170 | // There is a scope down policy, get a federation token with it 171 | 172 | // Trim the UUID down to a size that STS will accept 173 | String name = UUID.randomUUID().toString().substring(0, 31); 174 | 175 | GetFederationTokenRequest getFederationTokenRequest = GetFederationTokenRequest.builder() 176 | .name(name) 177 | .policy(optionalScopeDownJson.get()) 178 | .build(); 179 | 180 | GetFederationTokenResponse getFederationTokenResponse = stsClient.getFederationToken(getFederationTokenRequest); 181 | 182 | Credentials credentials = getFederationTokenResponse.credentials(); 183 | 184 | awsAccessKeyId = credentials.accessKeyId(); 185 | awsSecretAccessKey = credentials.secretAccessKey(); 186 | optionalSessionToken = Optional.of(credentials.sessionToken()); 187 | } else { 188 | // No scope down policy, just use the user's existing permissions 189 | awsCredentials = credentialsProvider.resolveCredentials(); 190 | awsAccessKeyId = awsCredentials.accessKeyId(); 191 | awsSecretAccessKey = awsCredentials.secretAccessKey(); 192 | 193 | if (awsCredentials instanceof AwsSessionCredentials) { 194 | optionalSessionToken = Optional.of(((AwsSessionCredentials) awsCredentials).sessionToken()); 195 | } 196 | } 197 | } else { 198 | // Assume a new role 199 | String roleArn = optionalRoleToAssume.get(); 200 | 201 | if (!roleArn.startsWith(ARN_AWS_IAM)) { 202 | // The role coming from the environment will be the full ARN, if this is just the role name add the proper prefix 203 | String accountId = getAccountId.apply(stsClient); 204 | 205 | roleArn = ARN_AWS_IAM + accountId + ":role/" + roleArn; 206 | } 207 | 208 | log.debug("Attempting to assume role: " + roleArn); 209 | 210 | AssumeRoleRequest.Builder assumeRoleRequestBuilder = AssumeRoleRequest.builder() 211 | .roleArn(roleArn) 212 | .roleSessionName("aws-iot-core-websockets-java"); 213 | 214 | // Add the scope down policy if there is one 215 | optionalScopeDownJson.ifPresent(assumeRoleRequestBuilder::policy); 216 | 217 | AssumeRoleRequest assumeRoleRequest = assumeRoleRequestBuilder.build(); 218 | AssumeRoleResponse assumeRoleResult = stsClient.assumeRole(assumeRoleRequest); 219 | 220 | Credentials credentials = assumeRoleResult.credentials(); 221 | awsSecretAccessKey = credentials.secretAccessKey(); 222 | awsAccessKeyId = credentials.accessKeyId(); 223 | optionalSessionToken = Optional.of(credentials.sessionToken()); 224 | } 225 | 226 | String algorithm = "AWS4-HMAC-SHA256"; 227 | String method = "GET"; 228 | String canonicalUri = "/mqtt"; 229 | 230 | String credentialScope = dateStamp + "/" + regionString + "/" + service + "/" + "aws4_request"; 231 | 232 | Tuple2 xAmzAlgorithm = Tuple.of("X-Amz-Algorithm", "AWS4-HMAC-SHA256"); 233 | Tuple2 xAmzCredential = Tuple.of("X-Amz-Credential", URLEncoder.encode(awsAccessKeyId + "/" + credentialScope, StandardCharsets.UTF_8)); 234 | Tuple2 xAmzDate = Tuple.of("X-Amz-Date", amzdate); 235 | Tuple2 xAmzSignedHeaders = Tuple.of(X_AMZ_SIGNED_HEADERS, "host"); 236 | 237 | String canonicalQueryString = String.join("&", 238 | xAmzAlgorithm.apply(this::tupleToParameter), 239 | xAmzCredential.apply(this::tupleToParameter), 240 | xAmzDate.apply(this::tupleToParameter), 241 | xAmzSignedHeaders.apply(this::tupleToParameter)); 242 | 243 | String canonicalHeaders = "host:" + clientEndpoint + ":443\n"; 244 | String payloadHash = sha256(""); 245 | String canonicalRequest = method + "\n" + canonicalUri + "\n" + canonicalQueryString + "\n" + canonicalHeaders + "\nhost\n" + payloadHash; 246 | 247 | String stringToSign = algorithm + "\n" + amzdate + "\n" + credentialScope + "\n" + sha256(canonicalRequest); 248 | byte[] signingKey = getSignatureKey(awsSecretAccessKey, dateStamp, regionString, service); 249 | String signature = sign(signingKey, stringToSign); 250 | 251 | Tuple2 xAmzSignature = Tuple.of("X-Amz-Signature", signature); 252 | 253 | canonicalQueryString = String.join("&", canonicalQueryString, 254 | xAmzSignature.apply(this::tupleToParameter)); 255 | 256 | if (optionalSessionToken.isPresent()) { 257 | Tuple2 xAmzSecurityToken = Tuple.of("X-Amz-Security-Token", URLEncoder.encode(optionalSessionToken.get(), StandardCharsets.UTF_8)); 258 | 259 | canonicalQueryString = String.join("&", 260 | canonicalQueryString, 261 | xAmzSecurityToken.apply(this::tupleToParameter)); 262 | } 263 | 264 | return "wss://" + clientEndpoint + canonicalUri + "?" + canonicalQueryString; 265 | } 266 | 267 | @NotNull 268 | private String tupleToParameter(String a, String b) { 269 | return String.join("=", a, b); 270 | } 271 | 272 | public Function2, Optional, StsClient> getStsClient = Function2., Optional, StsClient>of((optionalAwsCredentialsProviderChain, optionalRegion) -> { 273 | StsClientBuilder builder = StsClient.builder() 274 | .httpClientBuilder(apacheClientBuilder); 275 | optionalRegion.ifPresent(builder::region); 276 | optionalAwsCredentialsProviderChain.ifPresent(builder::credentialsProvider); 277 | 278 | return builder.build(); 279 | }).memoized(); 280 | 281 | public Function1 getAccountId = Function1.of( 282 | stsClient -> stsClient.getCallerIdentity(GetCallerIdentityRequest.builder().build()).account() 283 | ).memoized(); 284 | 285 | private String getEndpointAddressForRegion(Optional optionalRegion) { 286 | if (!endpointMap.containsKey(optionalRegion)) { 287 | DescribeEndpointRequest describeEndpointRequest = DescribeEndpointRequest.builder() 288 | .endpointType("iot:Data-ATS") 289 | .build(); 290 | String endpointAddress = getIotClient(optionalRegion).describeEndpoint(describeEndpointRequest).endpointAddress(); 291 | 292 | endpointMap.put(optionalRegion, endpointAddress); 293 | } 294 | 295 | return endpointMap.get(optionalRegion); 296 | } 297 | 298 | private IotClient getIotClient(Optional optionalRegion) { 299 | IotClientBuilder builder = IotClient.builder() 300 | .httpClientBuilder(apacheClientBuilder); 301 | optionalRegion.ifPresent(builder::region); 302 | 303 | return builder.build(); 304 | 305 | } 306 | 307 | private Region getDefaultRegionString() { 308 | AwsRegionProviderChain awsRegionProviderChain = new DefaultAwsRegionProviderChain(); 309 | return awsRegionProviderChain.getRegion(); 310 | } 311 | 312 | private byte[] HmacSHA256(String data, byte[] key) throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException { 313 | String algorithm = "HmacSHA256"; 314 | Mac mac = Mac.getInstance(algorithm); 315 | mac.init(new SecretKeySpec(key, algorithm)); 316 | return mac.doFinal(data.getBytes("UTF8")); 317 | } 318 | 319 | private byte[] getSignatureKey(String key, String dateStamp, String regionName, String serviceName) throws UnsupportedEncodingException, InvalidKeyException, NoSuchAlgorithmException { 320 | byte[] kSecret = ("AWS4" + key).getBytes("UTF8"); 321 | byte[] kDate = HmacSHA256(dateStamp, kSecret); 322 | byte[] kRegion = HmacSHA256(regionName, kDate); 323 | byte[] kService = HmacSHA256(serviceName, kRegion); 324 | byte[] kSigning = HmacSHA256("aws4_request", kService); 325 | 326 | return kSigning; 327 | } 328 | 329 | private String sign(byte[] key, String message) throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException { 330 | byte[] hash = HmacSHA256(message, key); 331 | return bytesToHex(hash); 332 | } 333 | 334 | // From: https://gist.github.com/avilches/750151 335 | private String sha256(String data) throws NoSuchAlgorithmException { 336 | MessageDigest md = MessageDigest.getInstance("SHA-256"); 337 | md.update(data.getBytes()); 338 | 339 | return bytesToHex(md.digest()); 340 | } 341 | 342 | // From: https://gist.github.com/avilches/750151 343 | private String bytesToHex(byte[] bytes) { 344 | StringBuilder result = new StringBuilder(); 345 | for (byte byt : bytes) result.append(Integer.toString((byt & 0xff) + 0x100, 16).substring(1)); 346 | return result.toString(); 347 | } 348 | } 349 | --------------------------------------------------------------------------------