use of com.google.api.client.util.Base64.encodeBase64String in project azure-iot-sdk-java by Azure.
the class IotHubServiceSasTokenTest method constructor_good_case_flow_check.
// Tests_SRS_SERVICE_SDK_JAVA_IOTHUBSERVICESASTOKEN_12_002: [The constructor shall create a target uri from the url encoded host name)]
// Tests_SRS_SERVICE_SDK_JAVA_IOTHUBSERVICESASTOKEN_12_003: [The constructor shall create a string to sign by concatenating the target uri and the expiry time string]
// Tests_SRS_SERVICE_SDK_JAVA_IOTHUBSERVICESASTOKEN_12_004: [The constructor shall create a key from the shared access key signing with HmacSHA256]
// Tests_SRS_SERVICE_SDK_JAVA_IOTHUBSERVICESASTOKEN_12_005: [The constructor shall compute the final signature by url encoding the signed key]
// Tests_SRS_SERVICE_SDK_JAVA_IOTHUBSERVICESASTOKEN_12_006: [The constructor shall concatenate the target uri, the signature, the expiry time and the key name using the format: "SharedAccessSignature sr=%s&sig=%s&se=%s&skn=%s"]
@Test
public void constructor_good_case_flow_check() throws Exception {
// Arrange
String cryptoProvider = "HmacSHA256";
String charset = "UTF-8";
String iotHubName = "b.c.d";
String hostName = "HOSTNAME." + iotHubName;
String sharedAccessKeyName = "ACCESSKEYNAME";
String policyName = "SharedAccessKey";
String sharedAccessKey = encodeBase64String("1234567890abcdefghijklmnopqrstvwxyz=".getBytes(StandardCharsets.UTF_8));
String connectionString = "HostName=" + hostName + ";SharedAccessKeyName=" + sharedAccessKeyName + ";" + policyName + "=" + sharedAccessKey;
IotHubConnectionString iotHubConnectionString = IotHubConnectionStringBuilder.createConnectionString(connectionString);
// Assert
new Expectations() {
URLEncoder urlEncoder;
System system;
final SecretKeySpec secretKeySpec;
Mac mac;
{
URLEncoder.encode(hostName.toLowerCase(), String.valueOf(StandardCharsets.UTF_8));
System.currentTimeMillis();
// Semmle flags this as sensitive call, but it is a false positive since it is for test purposes
// lgtm
byte[] body = { 1 };
secretKeySpec = new SecretKeySpec(body, cryptoProvider);
Mac.getInstance(cryptoProvider);
}
};
// Act
IotHubServiceSasToken iotHubServiceSasToken = new IotHubServiceSasToken(iotHubConnectionString);
}
use of com.google.api.client.util.Base64.encodeBase64String in project azure-iot-sdk-java by Azure.
the class ProvisioningServiceSasTokenTest method constructorCheckFormatSucceeded.
// Tests_SRS_PROVISIONING_SERVICE_SASTOKEN_12_002: [The constructor shall create a target uri from the url encoded host name)]
// Tests_SRS_PROVISIONING_SERVICE_SASTOKEN_12_003: [The constructor shall create a string to sign by concatenating the target uri and the expiry time string (one year)]
// Tests_SRS_PROVISIONING_SERVICE_SASTOKEN_12_004: [The constructor shall create a key from the shared access key signing with HmacSHA256]
// Tests_SRS_PROVISIONING_SERVICE_SASTOKEN_12_005: [The constructor shall compute the final signature by url encoding the signed key]
// Tests_SRS_PROVISIONING_SERVICE_SASTOKEN_12_006: [The constructor shall concatenate the target uri, the signature, the expiry time and the key name using the format: "SharedAccessSignature sr=%s&sig=%s&se=%s&skn=%s"]
// Tests_SRS_PROVISIONING_SERVICE_SASTOKEN_12_008: [The function shall return with the generated token]
@Test
public void constructorCheckFormatSucceeded() throws Exception {
// Arrange
String deviceProvisioningServiceName = "b.c.d";
String hostName = "HOSTNAME." + deviceProvisioningServiceName;
String sharedAccessKeyName = "ACCESSKEYNAME";
String policyName = "SharedAccessKey";
String sharedAccessKey = encodeBase64String("key".getBytes(StandardCharsets.UTF_8));
String connectionString = "HostName=" + hostName + ";SharedAccessKeyName=" + sharedAccessKeyName + ";" + policyName + "=" + sharedAccessKey;
ProvisioningConnectionString provisioningConnectionString = ProvisioningConnectionStringBuilder.createConnectionString(connectionString);
// Act
ProvisioningSasToken provisioningServiceSasToken = new ProvisioningSasToken(provisioningConnectionString);
String token = provisioningServiceSasToken.toString();
// Assert
assertTrue(token.contains("SharedAccessSignature sr=hostname.b.c.d&sig="));
assertTrue(token.contains("&se="));
assertTrue(token.contains("&skn=ACCESSKEYNAME"));
}
use of com.google.api.client.util.Base64.encodeBase64String in project azure-iot-sdk-java by Azure.
the class ProvisioningServiceSasTokenTest method constructorSucceeded.
// Tests_SRS_PROVISIONING_SERVICE_SASTOKEN_12_002: [The constructor shall create a target uri from the url encoded host name)]
// Tests_SRS_PROVISIONING_SERVICE_SASTOKEN_12_003: [The constructor shall create a string to sign by concatenating the target uri and the expiry time string]
// Tests_SRS_PROVISIONING_SERVICE_SASTOKEN_12_004: [The constructor shall create a key from the shared access key signing with HmacSHA256]
// Tests_SRS_PROVISIONING_SERVICE_SASTOKEN_12_005: [The constructor shall compute the final signature by url encoding the signed key]
// Tests_SRS_PROVISIONING_SERVICE_SASTOKEN_12_006: [The constructor shall concatenate the target uri, the signature, the expiry time and the key name using the format: "SharedAccessSignature sr=%s&sig=%s&se=%s&skn=%s"]
@Test
public void constructorSucceeded() throws Exception {
// Arrange
String cryptoProvider = "HmacSHA256";
String charset = "UTF-8";
String deviceProvisioningServiceName = "b.c.d";
String hostName = "HOSTNAME." + deviceProvisioningServiceName;
String sharedAccessKeyName = "ACCESSKEYNAME";
String policyName = "SharedAccessKey";
String sharedAccessKey = encodeBase64String("key".getBytes(StandardCharsets.UTF_8));
String connectionString = "HostName=" + hostName + ";SharedAccessKeyName=" + sharedAccessKeyName + ";" + policyName + "=" + sharedAccessKey;
ProvisioningConnectionString provisioningConnectionString = ProvisioningConnectionStringBuilder.createConnectionString(connectionString);
// Assert
new Expectations() {
URLEncoder urlEncoder;
System system;
final SecretKeySpec secretKeySpec;
Mac mac;
{
URLEncoder.encode(hostName.toLowerCase(), String.valueOf(StandardCharsets.UTF_8));
System.currentTimeMillis();
decodeBase64(sharedAccessKey.getBytes(charset));
// Semmle flags this as sensitive call, but it is a false positive since it is for test purposes
// lgtm
byte[] body = { 1 };
secretKeySpec = new SecretKeySpec(body, cryptoProvider);
Mac.getInstance(cryptoProvider);
}
};
// Act
ProvisioningSasToken provisioningServiceSasToken = new ProvisioningSasToken(provisioningConnectionString);
}
use of com.google.api.client.util.Base64.encodeBase64String in project azure-iot-sdk-java by Azure.
the class ContractAPIHttpTest method requestNonceWithDPSTPMSucceeds.
// SRS_ContractAPIHttp_25_004: [This method shall retrieve the Url by calling 'generateRegisterUrl' on an object for UrlPathBuilder.]
// SRS_ContractAPIHttp_25_005: [This method shall prepare the PUT request by setting following headers on a HttpRequest 1. User-Agent : User Agent String for the SDK 2. Accept : "application/json" 3. Content-Type: "application/json; charset=utf-8".]
// SRS_ContractAPIHttp_25_006: [This method shall set the SSLContext for the Http Request.]
// SRS_ContractAPIHttp_25_008: [If service return a status as 404 then this method shall trigger the callback to the user with the response message.]
@Test
public void requestNonceWithDPSTPMSucceeds() throws IOException, ProvisioningDeviceClientException {
// arrange
final byte[] expectedPayload = "testByte".getBytes(StandardCharsets.UTF_8);
ContractAPIHttp contractAPIHttp = createContractClass();
prepareRequestExpectations();
new NonStrictExpectations() {
{
mockedRequestData.getRegistrationId();
result = TEST_REGISTRATION_ID;
mockedRequestData.getEndorsementKey();
result = TEST_EK;
mockedRequestData.getStorageRootKey();
result = TEST_SRK;
mockedRequestData.getSslContext();
result = mockedSslContext;
mockedHttpRequest.send();
result = mockedHttpResponse;
ProvisioningDeviceClientExceptionManager.verifyHttpResponse(mockedHttpResponse);
result = new ProvisioningDeviceHubException("test Exception");
mockedHttpResponse.getStatus();
result = 401;
TpmRegistrationResultParser.createFromJson(new String(mockedHttpResponse.getBody()));
result = mockedTpmRegistrationResultParser;
mockedTpmRegistrationResultParser.getAuthenticationKey();
result = encodeBase64String("some auth key".getBytes(StandardCharsets.UTF_8));
new DeviceRegistrationParser(anyString, anyString, anyString, anyString);
result = mockedDeviceRegistrationParser;
mockedDeviceRegistrationParser.toJson();
result = "some json";
}
};
// act
contractAPIHttp.requestNonceForTPM(mockedRequestData, mockedResponseCallback, null);
// assert
prepareRequestVerifications(HttpMethod.PUT, 0);
new Verifications() {
{
new UrlPathBuilder(TEST_HOST_NAME, TEST_SCOPE_ID, ProvisioningDeviceClientTransportProtocol.HTTPS);
times = 1;
mockedUrlPathBuilder.generateRegisterUrl(TEST_REGISTRATION_ID);
times = 1;
mockedHttpRequest.setSSLContext(mockedSslContext);
times = 1;
mockedResponseCallback.run((ResponseData) any, null);
times = 1;
}
};
}
use of com.google.api.client.util.Base64.encodeBase64String in project gocd by gocd.
the class AgentRegistrationController method agentRequest.
@RequestMapping(value = "/admin/agent", method = RequestMethod.POST)
public ResponseEntity agentRequest(@RequestParam("hostname") String hostname, @RequestParam("uuid") String uuid, @RequestParam("location") String location, @RequestParam("usablespace") String usableSpaceStr, @RequestParam("operatingSystem") String os, @RequestParam("agentAutoRegisterKey") String agentAutoRegisterKey, @RequestParam("agentAutoRegisterResources") String agentAutoRegisterResources, @RequestParam("agentAutoRegisterEnvironments") String agentAutoRegisterEnvs, @RequestParam("agentAutoRegisterHostname") String agentAutoRegisterHostname, @RequestParam("elasticAgentId") String elasticAgentId, @RequestParam("elasticPluginId") String elasticPluginId, @RequestParam("token") String token, HttpServletRequest request) {
final String ipAddress = request.getRemoteAddr();
LOG.debug("Processing registration request from agent [{}/{}]", hostname, ipAddress);
boolean keyEntry;
String preferredHostname = hostname;
boolean isElasticAgent = elasticAgentAutoregistrationInfoPresent(elasticAgentId, elasticPluginId);
try {
if (!encodeBase64String(hmac().doFinal(uuid.getBytes())).equals(token)) {
String message = "Not a valid token.";
LOG.error("Rejecting request for registration. Error: HttpCode=[{}] Message=[{}] UUID=[{}] Hostname=[{}]" + "ElasticAgentID=[{}] PluginID=[{}]", FORBIDDEN, message, uuid, hostname, elasticAgentId, elasticPluginId);
return new ResponseEntity<>(message, FORBIDDEN);
}
boolean shouldAutoRegister = shouldAutoRegister(agentAutoRegisterKey, isElasticAgent);
if (shouldAutoRegister) {
preferredHostname = getPreferredHostname(agentAutoRegisterHostname, hostname);
} else {
if (elasticAgentAutoregistrationInfoPresent(elasticAgentId, elasticPluginId)) {
String message = String.format("Elastic agent registration requires an auto-register agent key to be" + " setup on the server. The agentAutoRegisterKey: [%s] is either not provided or expired. Agent-id: [%s], Plugin-id: [%s]", agentAutoRegisterKey, elasticAgentId, elasticPluginId);
LOG.error("Rejecting request for registration. Error: HttpCode=[{}] Message=[{}] UUID=[{}] Hostname=[{}]" + "ElasticAgentID=[{}] PluginID=[{}]", UNPROCESSABLE_ENTITY, message, uuid, hostname, elasticAgentId, elasticPluginId);
return new ResponseEntity<>(message, UNPROCESSABLE_ENTITY);
}
}
Agent agent = createAgentFromRequest(uuid, preferredHostname, ipAddress, elasticAgentId, elasticPluginId);
agent.validate();
if (agent.hasErrors()) {
List<ConfigErrors> errors = agent.errorsAsList();
throw new GoConfigInvalidException(null, new AllConfigErrors(errors));
}
if (partialElasticAgentAutoregistrationInfo(elasticAgentId, elasticPluginId)) {
String message = "Elastic agents must submit both elasticAgentId and elasticPluginId.";
LOG.error("Rejecting request for registration. Error: HttpCode=[{}] Message=[{}] UUID=[{}] Hostname=[{}]" + "ElasticAgentID=[{}] PluginID=[{}]", UNPROCESSABLE_ENTITY, message, uuid, hostname, elasticAgentId, elasticPluginId);
return new ResponseEntity<>(message, UNPROCESSABLE_ENTITY);
}
if (elasticAgentIdAlreadyRegistered(elasticAgentId, elasticPluginId)) {
String message = "Duplicate Elastic agent Id used to register elastic agent.";
LOG.error("Rejecting request for registration. Error: HttpCode=[{}] Message=[{}] UUID=[{}] Hostname=[{}]" + "ElasticAgentID=[{}] PluginID=[{}]", UNPROCESSABLE_ENTITY, message, uuid, hostname, elasticAgentId, elasticPluginId);
return new ResponseEntity<>(message, UNPROCESSABLE_ENTITY);
}
if (shouldAutoRegister && !agentService.isRegistered(uuid)) {
LOG.info("[Agent Auto Registration] Auto registering agent with uuid {} ", uuid);
agent.setEnvironments(agentAutoRegisterEnvs);
agent.setResources(agentAutoRegisterResources);
agentService.register(agent);
if (agent.hasErrors()) {
throw new GoConfigInvalidException(null, new AllConfigErrors(agent.errorsAsList()).asString());
}
}
boolean registeredAlready = agentService.isRegistered(uuid);
long usableSpace = Long.parseLong(usableSpaceStr);
AgentRuntimeInfo agentRuntimeInfo = AgentRuntimeInfo.fromServer(agent, registeredAlready, location, usableSpace, os);
if (elasticAgentAutoregistrationInfoPresent(elasticAgentId, elasticPluginId)) {
agentRuntimeInfo = ElasticAgentRuntimeInfo.fromServer(agentRuntimeInfo, elasticAgentId, elasticPluginId);
}
keyEntry = agentService.requestRegistration(agentRuntimeInfo);
final HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
return new ResponseEntity<>("", httpHeaders, keyEntry ? OK : ACCEPTED);
} catch (Exception e) {
LOG.error("Error occurred during agent registration process. Error: HttpCode=[{}] Message=[{}] UUID=[{}] " + "Hostname=[{}] ElasticAgentID=[{}] PluginID=[{}]", UNPROCESSABLE_ENTITY, getErrorMessage(e), uuid, hostname, elasticAgentId, elasticPluginId, e);
return new ResponseEntity<>(String.format("Error occurred during agent registration process: %s", getErrorMessage(e)), UNPROCESSABLE_ENTITY);
}
}
Aggregations