Skip to content

Commit

Permalink
Merge pull request #11 from GovTechSG/development
Browse files Browse the repository at this point in the history
Update and Fix Issue #6 - Failed unit test-cases.
  • Loading branch information
Kelvin Wijaya authored Jan 22, 2019
2 parents 964b62c + 938ca4d commit a6c5872
Show file tree
Hide file tree
Showing 10 changed files with 156 additions and 94 deletions.
11 changes: 10 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,7 +1,16 @@
# Autosave files
*~
# vs project
# Project related
.vs/
.idea/

# Output files
ApiUtilLib/bin
ApiUtilLib/obj

# Output Test files
ApiUtilLibTest/bin
ApiUtilLibTest/obj

# build
[Oo]bj/
Expand Down
99 changes: 63 additions & 36 deletions ApiUtilLib/ApiAuthorization.cs
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,19 @@ public static RSACryptoServiceProvider PrivateKeyFromP12(string certificateFileN
public static string GetL2SignatureFromPEM(string filename, string message, string passPhrase)
{
Logger.LogEnterExit(LoggerBase.Args(filename, "***password***"));
if (String.IsNullOrEmpty(message))
{
Logger.LogError("{0} must not be null or empty.", nameof(message));

throw new ArgumentNullException(nameof(message));
}

if (String.IsNullOrEmpty(filename))
{
Logger.LogError("{0} must not be null or empty.", nameof(filename));

throw new ArgumentNullException(nameof(filename));
}
string result = null;
try
{
Expand Down Expand Up @@ -394,52 +407,66 @@ string realm
, string timestamp = null
, string version = "1.0")
{
Logger.LogEnter(LoggerBase.Args(realm, authPrefix, httpMethod, urlPath, appId, secret, formList == null ? null : formList.ToFormData(), privateKey, nonce, timestamp, version));
String nullValueErrMsg = "One or more required parameters are missing!";
try
{
Logger.LogEnter(LoggerBase.Args(realm, authPrefix, httpMethod, urlPath, appId, secret, formList == null ? null : formList.ToFormData(), privateKey, nonce, timestamp, version));

Logger.LogDebug("URL:: {0}", urlPath);
Logger.LogDebug("URL:: {0}", urlPath);
if (String.IsNullOrEmpty(authPrefix))
{
Logger.LogError(nullValueErrMsg);
throw new ArgumentNullException(nameof(authPrefix));
}

authPrefix = authPrefix.ToLower();

// Generate the nonce value
nonce = nonce ?? ApiAuthorization.NewNonce().ToString();
timestamp = timestamp ?? ApiAuthorization.NewTimestamp().ToString();
authPrefix = authPrefix.ToLower();

SignatureMethod signatureMethod = SignatureMethod.HMACSHA256;
if (secret == null)
{
signatureMethod = SignatureMethod.SHA256withRSA;
}
// Generate the nonce value
nonce = nonce ?? ApiAuthorization.NewNonce().ToString();
timestamp = timestamp ?? ApiAuthorization.NewTimestamp().ToString();

SignatureMethod signatureMethod = SignatureMethod.HMACSHA256;
if (secret == null)
{
signatureMethod = SignatureMethod.SHA256withRSA;
}

String baseString = BaseString(authPrefix, signatureMethod
, appId, urlPath, httpMethod
, formList, nonce, timestamp, version);
String baseString = BaseString(authPrefix, signatureMethod
, appId, urlPath, httpMethod
, formList, nonce, timestamp, version);

String base64Token = "";
if (secret != null)
{
base64Token = baseString.L1Signature(secret);
}
else
{
base64Token = baseString.L2Signature(privateKey);
}
String base64Token = "";
if (secret != null)
{
base64Token = baseString.L1Signature(secret);
}
else
{
base64Token = baseString.L2Signature(privateKey);
}

var tokenList = new ApiList();
var tokenList = new ApiList();

tokenList.Add("realm", realm);
tokenList.Add(authPrefix + "_app_id", appId);
tokenList.Add(authPrefix + "_nonce", nonce);
tokenList.Add(authPrefix + "_signature_method", signatureMethod.ToString());
tokenList.Add(authPrefix + "_timestamp", timestamp);
tokenList.Add(authPrefix + "_version", version);
tokenList.Add(authPrefix + "_signature", base64Token);
tokenList.Add("realm", realm);
tokenList.Add(authPrefix + "_app_id", appId);
tokenList.Add(authPrefix + "_nonce", nonce);
tokenList.Add(authPrefix + "_signature_method", signatureMethod.ToString());
tokenList.Add(authPrefix + "_timestamp", timestamp);
tokenList.Add(authPrefix + "_version", version);
tokenList.Add(authPrefix + "_signature", base64Token);

string authorizationToken = string.Format("{0} {1}", authPrefix.Substring(0, 1).ToUpperInvariant() + authPrefix.Substring(1), tokenList.ToString(", ", false, true));
string authorizationToken = string.Format("{0} {1}", authPrefix.Substring(0, 1).ToUpperInvariant() + authPrefix.Substring(1), tokenList.ToString(", ", false, true));

Logger.LogDebug("Token :: {0}", authorizationToken);
Logger.LogDebug("Token :: {0}", authorizationToken);

Logger.LogExit(LoggerBase.Args(authorizationToken));
return authorizationToken;
Logger.LogExit(LoggerBase.Args(authorizationToken));
return authorizationToken;
}
catch (Exception ex)
{
throw ex;
}
}

public static int HttpRequest(Uri url, string token = null, ApiList postData = null, HttpMethod httpMethod = HttpMethod.GET, bool ignoreServerCert = false)
Expand Down Expand Up @@ -567,7 +594,7 @@ public static void InitiateSSLTrust()
}
catch (Exception ex)
{
Console.WriteLine("{0}", ex);
throw ex;
}
}

Expand Down
10 changes: 5 additions & 5 deletions ApiUtilLibTest/AuthorizationTokenTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,10 @@ static string GetLocalPath(string relativeFileName)
const string nonce = "-5816789581922453013";
const string timestamp = "1502199514462";

//[Test]
[Test]
public void Test_L1_Basic_Test()
{
var expectedTokenL1 = "Api_prefix_l1 realm=\"http://example.api.test/token\",api_prefix_l1_timestamp=\"1502199514462\",api_prefix_l1_nonce=\"-5816789581922453013\",api_prefix_l1_app_id=\"app-id-lpX54CVNltS0ye03v2mQc0b\",api_prefix_l1_signature_method=\"HMACSHA256\",api_prefix_l1_version=\"1.0\",api_prefix_l1_signature=\"loz2Hp2wqiK8RxWjkI6Y6Y4OzmOS/QVPevT8Z43TRM4=\"";
var expectedTokenL1 = "Api_prefix_l1 realm=\"http://example.api.test/token\", api_prefix_l1_app_id=\"app-id-lpX54CVNltS0ye03v2mQc0b\", api_prefix_l1_nonce=\"-5816789581922453013\", api_prefix_l1_signature_method=\"HMACSHA256\", api_prefix_l1_timestamp=\"1502199514462\", api_prefix_l1_version=\"1.0\", api_prefix_l1_signature=\"loz2Hp2wqiK8RxWjkI6Y6Y4OzmOS/QVPevT8Z43TRM4=\"";

var authorizationToken = ApiAuthorization.Token(
realm
Expand All @@ -55,13 +55,13 @@ public void Test_L1_Basic_Test()
, nonce: nonce
);

Assert.AreEqual(expectedTokenL1, authorizationToken);
Assert.AreEqual(expectedTokenL1, authorizationToken);
}

//[Test]
[Test]
public void Test_L2_Basic_Test()
{
var expectedTokenL2 = "Api_prefix_l2 realm=\"http://example.api.test/token\",api_prefix_l2_timestamp=\"1502199514462\",api_prefix_l2_nonce=\"-5816789581922453013\",api_prefix_l2_app_id=\"app-id-lpX54CVNltS0ye03v2mQc0b\",api_prefix_l2_signature_method=\"SHA256withRSA\",api_prefix_l2_version=\"1.0\",api_prefix_l2_signature=\"EZuFn/n3dxJ4OA9nkdM3yvw76azvyx/HKptQoWzTNWHxMB/2FyurbbpsSb16yNU4bOzRgHlFTZZzbJeZd211M7tLfRC/YQ1Mc2aIxufG7c7H3/3IZ0WdfHIJlF+XwHOR4U5sjRhbCBwSOZzHp6V2a/nmm+CYTjW2LBHxG7aB1wNI6V1PGDp+ePVr8uoyd4MD9nJj5IqLlljtpWCBUJsa7ZZdXgwbStxAdVA3j2lk3FAH9BzaKTQV0msB50Ou/itAw95pqH4RGrWjcuUETUN82JG154SrT/+hqXlmgsgl+6vui7kyCIGnQjhH+3ZSIp/91nJKW8/1hDcNKWQzuoIS9G23rJzPIuStc1f8y/YvXjUSxNTItb4DcSGwqOs1W8+ejLofW/HDBENhhL66ZZaO0EbJmMWJDp+r7w+RtrlRa2QLsuocuAYAsc8FbhW8SBowIHt/BpuIE21SCfXhbbqYmi0WY+YjJxJ79bNsf7OzH57wQln2Ri6jUtRsCez3rP+714aSAJMLKzJPrsUsiefQDuDjl+g7Fs+Ge5eCv3EOu36qmBEAwvS8oNU8eKa0ZnuXTZrvVEyAAgqQXjv7V4tklKImHMhBv3CqWHGtmxCIqFJuJ71ss81kOJ9pc1otyMzKvSZtVyxaOFgE1hTPfsA6Y5pQayhVikeCMfX8u/uFSmM=\"";
var expectedTokenL2 = "Api_prefix_l2 realm=\"http://example.api.test/token\", api_prefix_l2_app_id=\"app-id-lpX54CVNltS0ye03v2mQc0b\", api_prefix_l2_nonce=\"-5816789581922453013\", api_prefix_l2_signature_method=\"SHA256withRSA\", api_prefix_l2_timestamp=\"1502199514462\", api_prefix_l2_version=\"1.0\", api_prefix_l2_signature=\"EZuFn/n3dxJ4OA9nkdM3yvw76azvyx/HKptQoWzTNWHxMB/2FyurbbpsSb16yNU4bOzRgHlFTZZzbJeZd211M7tLfRC/YQ1Mc2aIxufG7c7H3/3IZ0WdfHIJlF+XwHOR4U5sjRhbCBwSOZzHp6V2a/nmm+CYTjW2LBHxG7aB1wNI6V1PGDp+ePVr8uoyd4MD9nJj5IqLlljtpWCBUJsa7ZZdXgwbStxAdVA3j2lk3FAH9BzaKTQV0msB50Ou/itAw95pqH4RGrWjcuUETUN82JG154SrT/+hqXlmgsgl+6vui7kyCIGnQjhH+3ZSIp/91nJKW8/1hDcNKWQzuoIS9G23rJzPIuStc1f8y/YvXjUSxNTItb4DcSGwqOs1W8+ejLofW/HDBENhhL66ZZaO0EbJmMWJDp+r7w+RtrlRa2QLsuocuAYAsc8FbhW8SBowIHt/BpuIE21SCfXhbbqYmi0WY+YjJxJ79bNsf7OzH57wQln2Ri6jUtRsCez3rP+714aSAJMLKzJPrsUsiefQDuDjl+g7Fs+Ge5eCv3EOu36qmBEAwvS8oNU8eKa0ZnuXTZrvVEyAAgqQXjv7V4tklKImHMhBv3CqWHGtmxCIqFJuJ71ss81kOJ9pc1otyMzKvSZtVyxaOFgE1hTPfsA6Y5pQayhVikeCMfX8u/uFSmM=\"";

var authorizationToken = ApiAuthorization.Token(
realm
Expand Down
66 changes: 40 additions & 26 deletions ApiUtilLibTest/BaseService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,6 @@ internal void downloadFile(string sourceURL, string downloadPath)
}
catch (Exception ex)
{
Console.WriteLine("Exception: " + ex);
throw ex;
}
}
Expand All @@ -100,11 +99,9 @@ internal void SetDetaultParams(TestParam paramFile)
apiList = new ApiList();
SetApiList(paramFile.apiParam.formData);
SetApiList(paramFile.apiParam.queryString);
timeStamp = paramFile.apiParam.timestamp;
if (paramFile.apiParam.timestamp.IsNullOrEmpty())
timeStamp = Convert.ToInt32(DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString(), 10).ToString();
timeStamp = paramFile.apiParam.timestamp ?? "%s";
version = paramFile.apiParam.version ?? "1.0";
nonce = paramFile.apiParam.nonce ?? ApiUtilLib.ApiAuthorization.NewNonce();
nonce = paramFile.apiParam.nonce ?? "%s";
authPrefix = paramFile.apiParam.authPrefix;
appId = paramFile.apiParam.appID;
testId = paramFile.id;
Expand Down Expand Up @@ -134,32 +131,49 @@ internal void SetApiList(Dictionary<object, object> data = null)
var key = item.Key ?? "";
var value = item.Value ?? "";

if (value.ToString().StartsWith("{", StringComparison.InvariantCulture) && value.ToString().EndsWith("}", StringComparison.InvariantCulture))
value = "";

string[] _subArry = { "" };
string val = null;
if (!value.ToString().IsNullOrEmpty())
String value_s = value.ToString().Trim();

if (!key.ToString().IsNullOrEmpty())
{
val = value.ToString().Trim().RemoveString(new string[] { "[", "]", "\\", "\\ ", " \\", "\"", "\\ ", "\n", " " }).Unescape();
_subArry = val.Split(',');
}
string[] _queryParams = { "" };
string val = null;

if (!value_s.IsNullOrEmpty() && !(value_s.StartsWith("{", StringComparison.InvariantCulture) && value_s.EndsWith("}", StringComparison.InvariantCulture)))
{

val = value_s.RemoveString(new string[] { "\\", "\\ ", " \\", "\"", "\\ ", "\n" }).Unescape();

if (val == "True")
val = "true";
if (val == "False")
val = "false";
if (val.StartsWith("[", StringComparison.InvariantCulture) && val.EndsWith("]", StringComparison.InvariantCulture))
{

string[] _paramValues = { "" };
val = val.RemoveString(new string[] { "[", "]", " " });
_paramValues = val.Split(',');
foreach (var paramvalue in _paramValues)
{
var _paramvalue = paramvalue;
apiList.Add(key.ToString(), _paramvalue.Unescape());
}

}
else
{
apiList.Add(key.ToString(), val);
}
}
else
{
apiList.Add(key.ToString(), val);
}

foreach (var subArry in _subArry)
{
var _val = subArry;
if (_val == "True")
_val = "true";
if (_val == "False")
_val = "false";

if (!key.ToString().IsNullOrEmpty())
apiList.Add(key.ToString(), _val);
}
}
}
}
catch (Exception ex)
}catch (Exception ex)
{
throw ex;
}
Expand Down
8 changes: 2 additions & 6 deletions ApiUtilLibTest/BaseStringTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public void BaseString_Basic_Test()
Assert.AreEqual(expectedBaseString, baseString);
}

//[Test]
[Test]
public void BaseString_BugTest()
{

Expand All @@ -43,7 +43,7 @@ public void BaseString_BugTest()
formData.Add("MessageBody", "[{}]");

var url = "https://test.example.com:443/api/v1/rest/level1/in-in/?ap=裕廊坊%20心邻坊";
var expectedBaseString = "GET&https://test.example.com/api/v1/rest/level1/in-in/&ap=裕廊坊 心邻坊&auth_prefix_app_id=app-id-lpX54CVNltS0ye03v2mQc0b&auth_prefix_nonce=1355584618267440511&auth_prefix_signature_method=HMACSHA256&auth_prefix_timestamp=1502175057654&auth_prefix_version=1.0";
var expectedBaseString = "GET&https://test.example.com/api/v1/rest/level1/in-in/&Action=SendMessage&MessageBody=[{}]&ap=裕廊坊 心邻坊&auth_prefix_app_id=app-id-lpX54CVNltS0ye03v2mQc0b&auth_prefix_nonce=1355584618267440511&auth_prefix_signature_method=HMACSHA256&auth_prefix_timestamp=1502175057654&auth_prefix_version=1.0";

var baseString = ApiAuthorization.BaseString(
"auth_prefix",
Expand All @@ -57,10 +57,6 @@ public void BaseString_BugTest()
"1.0"
);


//Console.WriteLine("\n>>>BaseString :: '{0}'<<<", baseString);

// Console.WriteLine("\n---Lab 3.2---");
Assert.AreEqual(expectedBaseString, baseString);
}

Expand Down
2 changes: 1 addition & 1 deletion ApiUtilLibTest/CommonExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ public static string GetCharp(Dictionary<string,string> value)
{
try
{
var result = value.Where(c => c.Key == "charp").FirstOrDefault().Value;
var result = value.Where(c => c.Key == "c#").FirstOrDefault().Value;
if (result==null)
result = value.Where(c => c.Key == "default").FirstOrDefault().Value;

Expand Down
Loading

0 comments on commit a6c5872

Please sign in to comment.