Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@

public abstract class Signer {

private final static Signer HMACSHA1_SIGNER = new com.aliyuncs.auth.signers.HmacSHA1Signer();
private final static Signer HMACSHA256_SIGNER = new SignatureV2HmacSHA256Signer();
private final static Signer SHA256_WITH_RSA_SIGNER = new com.aliyuncs.auth.signers.SHA256withRSASigner();
private final static Signer BEARER_TOKEN_SIGNER = new com.aliyuncs.auth.signers.BearerTokenSigner();
// Signature V3
Expand All @@ -39,7 +39,7 @@ public static Signer getSigner(AlibabaCloudCredentials credentials) {
} else if (credentials instanceof BearerTokenCredentials) {
return BEARER_TOKEN_SIGNER;
} else {
return HMACSHA1_SIGNER;
return HMACSHA256_SIGNER;
}
}

Expand All @@ -61,7 +61,7 @@ public static Signer getSigner(AlibabaCloudCredentials credentials, SignatureVer
} else if (credentials instanceof BearerTokenCredentials) {
return BEARER_TOKEN_SIGNER;
} else {
return HMACSHA1_SIGNER;
return HMACSHA256_SIGNER;
}
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package com.aliyuncs.auth.signers;

import com.aliyuncs.auth.AlibabaCloudCredentials;
import com.aliyuncs.auth.Signer;

import java.nio.charset.Charset;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;

public class SignatureV2HmacSHA256Signer extends Signer {

private static final Charset ENCODING = Charset.forName("UTF-8");
private static final String ALGORITHM_NAME = "HmacSHA256";

@Override
public String signString(String stringToSign, String accessKeySecret) {
try {
Mac mac = Mac.getInstance(ALGORITHM_NAME);
mac.init(new SecretKeySpec(accessKeySecret.getBytes(ENCODING), ALGORITHM_NAME));
return DatatypeConverter.printBase64Binary(mac.doFinal(stringToSign.getBytes(ENCODING)));
} catch (NoSuchAlgorithmException e) {
throw new IllegalArgumentException(e.toString());
} catch (InvalidKeyException e) {
throw new IllegalArgumentException(e.toString());
}
}

@Override
public String signString(String stringToSign, AlibabaCloudCredentials credentials) {
return signString(stringToSign, credentials.getAccessKeySecret());
}

@Override
public String getSignerName() {
return "HMAC-SHA256";
}

@Override
public String getSignerVersion() {
return "1.0";
}

@Override
public String getSignerType() {
return null;
}

@Override
public byte[] hash(byte[] raw) throws NoSuchAlgorithmException {
return null;
}

@Override
public String getContent() {
return null;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.*;

@PowerMockIgnore("javax.net.ssl.*")
@PowerMockIgnore({"javax.net.ssl.*", "javax.xml.*", "org.xml.*", "org.w3c.*", "com.sun.org.apache.*"})
@RunWith(PowerMockRunner.class)
@PrepareForTest({HttpUtil.class, LogUtils.class})
public class DefaultAcsClientTest {
Expand Down
166 changes: 166 additions & 0 deletions aliyun-java-sdk-core/src/test/java/com/aliyuncs/SignatureV2Test.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
package com.aliyuncs;

import com.aliyuncs.auth.AlibabaCloudCredentials;
import com.aliyuncs.auth.BasicCredentials;
import com.aliyuncs.auth.BasicSessionCredentials;
import com.aliyuncs.auth.Credential;
import com.aliyuncs.auth.SignatureVersion;
import com.aliyuncs.auth.Signer;
import com.aliyuncs.auth.signers.SignatureAlgorithm;
import com.aliyuncs.http.HttpRequest;
import com.aliyuncs.http.HttpResponse;
import com.aliyuncs.http.IHttpClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.http.ProtocolType;
import com.aliyuncs.profile.DefaultProfile;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.ArgumentCaptor;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.net.URI;
import java.net.URLDecoder;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

public class SignatureV2Test {

@Test
public void defaultRequestsUseSha256() throws Exception {
for (boolean rpc : new boolean[]{true, false}) {
for (MethodType method : new MethodType[]{MethodType.GET, MethodType.POST}) {
for (boolean sts : new boolean[]{false, true}) {
AlibabaCloudCredentials credentials = sts
? new BasicSessionCredentials("test-key", "test-secret", "test-token")
: new BasicCredentials("test-key", "test-secret");
DefaultAcsClient client = client(credentials);
AcsRequest<AcsResponse> request = request(rpc, method);
client.doAction(request);
assertV2Request(client, request, rpc, sts);
}
}
}
}

@Test
public void legacyCredentialOverloadUsesSha256() throws Exception {
DefaultAcsClient client = client(new BasicCredentials("test-key", "test-secret"));
AcsRequest<AcsResponse> request = request(true, MethodType.GET);
client.doAction(request, "cn-hangzhou", new Credential("test-key", "test-secret"));
assertV2Request(client, request, true, false);
}

@Test
public void v3StillUsesExistingProtocolAndHexSignature() throws Exception {
for (boolean rpc : new boolean[]{true, false}) {
DefaultAcsClient client = client(new BasicCredentials("test-key", "test-secret"));
client.setSignatureVersion(SignatureVersion.V3);
Assert.assertEquals(SignatureAlgorithm.ACS3_HMAC_SHA256, client.getSignatureAlgorithm());
AcsRequest<AcsResponse> request = request(rpc, MethodType.POST);
client.doAction(request);
HttpRequest sent = sentRequest(client);
String stringToSign = request.getSysStrToSign();
if (rpc) {
stringToSign = "ACS3-HMAC-SHA256\n" + hex(MessageDigest.getInstance("SHA-256")
.digest(stringToSign.getBytes("UTF-8")));
}
Assert.assertTrue(sent.getSysHeaders().get("Authorization").startsWith(
"ACS3-HMAC-SHA256 Credential=test-key,Signature="
+ hex(hmac("HmacSHA256", stringToSign, "test-secret")) + ",SignedHeaders="));
Assert.assertNotNull(sent.getSysHeaders().get("x-acs-content-sha256"));
}
}

@Test
public void sha256MatchesRfc4231Vector() {
Signer signer = Signer.getSigner(new BasicCredentials("test-key", "unused"));
Assert.assertEquals(DatatypeConverter.printBase64Binary(DatatypeConverter.parseHexBinary(
"B0344C61D8DB38535CA8AFCEAF0BF12B881DC200C9833DA726E9376C2E32CFF7")),
signer.signString("Hi There", "\013\013\013\013\013\013\013\013\013\013"
+ "\013\013\013\013\013\013\013\013\013\013"));
Assert.assertNull(signer.getSignerType());
Assert.assertNull(signer.getContent());
}

private DefaultAcsClient client(AlibabaCloudCredentials credentials) throws Exception {
DefaultAcsClient client = new DefaultAcsClient(DefaultProfile.getProfile("cn-hangzhou"), credentials);
IHttpClient httpClient = mock(IHttpClient.class);
HttpResponse response = new HttpResponse();
response.setStatus(200);
when(httpClient.syncInvoke(any(HttpRequest.class))).thenReturn(response);
client.setHttpClient(httpClient);
return client;
}

private AcsRequest<AcsResponse> request(boolean rpc, MethodType method) {
AcsRequest<AcsResponse> request;
if (rpc) {
request = new RpcAcsRequest<AcsResponse>("Ecs", "2014-05-26", "DescribeRegions") {
@Override
public Class<AcsResponse> getResponseClass() {
return AcsResponse.class;
}
};
} else {
RoaAcsRequest<AcsResponse> roa = new RoaAcsRequest<AcsResponse>("CS", "2015-12-15", "DescribeRegions") {
@Override
public Class<AcsResponse> getResponseClass() {
return AcsResponse.class;
}
};
roa.setSysUriPattern("/regions");
request = roa;
}
request.setSysMethod(method);
request.setSysProtocol(ProtocolType.HTTPS);
request.setSysEndpoint("example.test");
return request;
}

private void assertV2Request(DefaultAcsClient client, AcsRequest<AcsResponse> request,
boolean rpc, boolean sts) throws Exception {
HttpRequest sent = sentRequest(client);
String expected = DatatypeConverter.printBase64Binary(hmac("HmacSHA256",
request.getSysStrToSign(), "test-secret" + (rpc ? "&" : "")));
if (rpc) {
Map<String, String> query = new HashMap<String, String>();
for (String pair : new URI(sent.getSysUrl()).getRawQuery().split("&")) {
String[] parts = pair.split("=", 2);
query.put(URLDecoder.decode(parts[0], "UTF-8"), URLDecoder.decode(parts[1], "UTF-8"));
}
Assert.assertEquals("HMAC-SHA256", query.get("SignatureMethod"));
Assert.assertEquals("1.0", query.get("SignatureVersion"));
Assert.assertEquals(expected, query.get("Signature"));
Assert.assertEquals(sts ? "test-token" : null, query.get("SecurityToken"));
} else {
Assert.assertEquals("HMAC-SHA256", sent.getSysHeaders().get("x-acs-signature-method"));
Assert.assertEquals("1.0", sent.getSysHeaders().get("x-acs-signature-version"));
Assert.assertEquals("acs test-key:" + expected, sent.getSysHeaders().get("Authorization"));
Assert.assertEquals(sts ? "test-token" : null, sent.getSysHeaders().get("x-acs-security-token"));
}
}

private HttpRequest sentRequest(DefaultAcsClient client) throws Exception {
ArgumentCaptor<HttpRequest> capture = ArgumentCaptor.forClass(HttpRequest.class);
verify(client.getHttpClient()).syncInvoke(capture.capture());
return capture.getValue();
}

private byte[] hmac(String algorithm, String value, String secret) throws Exception {
Mac mac = Mac.getInstance(algorithm);
mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), algorithm));
return mac.doFinal(value.getBytes("UTF-8"));
}

private String hex(byte[] value) {
return DatatypeConverter.printHexBinary(value).toLowerCase(java.util.Locale.ROOT);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,20 +12,23 @@ public void getSignerReturnSha256WithRSASigner() {
AlibabaCloudCredentials credentials = mock(KeyPairCredentials.class);
Signer signer = Signer.getSigner(credentials, SignatureVersion.V1, null);
Assert.assertEquals(true, com.aliyuncs.auth.signers.SHA256withRSASigner.class.isAssignableFrom(signer.getClass()));
Assert.assertSame(signer, Signer.getSigner(credentials));
}

@Test
public void getSignerReturnBearerTokenSigner() {
AlibabaCloudCredentials credentials = mock(BearerTokenCredentials.class);
Signer signer = Signer.getSigner(credentials, SignatureVersion.V1, null);
Assert.assertEquals(true, com.aliyuncs.auth.signers.BearerTokenSigner.class.isAssignableFrom(signer.getClass()));
Assert.assertSame(signer, Signer.getSigner(credentials));
}

@Test
public void getSignerReturnHmacSHA1Signer() {
public void getSignerReturnSignatureV2HmacSHA256Signer() {
AlibabaCloudCredentials credentials = mock(AlibabaCloudCredentials.class);
Signer signer = Signer.getSigner(credentials, SignatureVersion.V1, null);
Assert.assertEquals(true, com.aliyuncs.auth.signers.HmacSHA1Signer.class.isAssignableFrom(signer.getClass()));
Assert.assertTrue(signer instanceof SignatureV2HmacSHA256Signer);
Assert.assertTrue(Signer.getSigner(credentials) instanceof SignatureV2HmacSHA256Signer);
}

@Test
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package com.aliyuncs.auth.signers;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import javax.crypto.Mac;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;

import static org.mockito.ArgumentMatchers.any;

@RunWith(PowerMockRunner.class)
@PrepareForTest({SignatureV2HmacSHA256Signer.class, Mac.class})
@PowerMockIgnore({"javax.xml.*", "org.xml.*", "org.w3c.*"})
public class SignatureV2HmacSHA256SignerTest {
@Rule
public ExpectedException thrown = ExpectedException.none();

@Test
public void failWhenSha256IsUnavailable() throws Exception {
PowerMockito.mockStatic(Mac.class);
PowerMockito.when(Mac.getInstance("HmacSHA256"))
.thenThrow(new NoSuchAlgorithmException("HmacSHA256 is unavailable"));
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("HmacSHA256 is unavailable");
new SignatureV2HmacSHA256Signer().signString("message", "test-secret");
}

@Test
public void failWhenProviderRejectsKey() throws Exception {
PowerMockito.mockStatic(Mac.class);
Mac mac = PowerMockito.mock(Mac.class);
PowerMockito.when(Mac.getInstance("HmacSHA256")).thenReturn(mac);
PowerMockito.doThrow(new InvalidKeyException("Provider rejected key")).when(mac).init(any(Key.class));
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("Provider rejected key");
new SignatureV2HmacSHA256Signer().signString("message", "test-secret");
}
}
Loading