Skip to content

Commit a6c5872

Browse files
author
Kelvin Wijaya
authored
Merge pull request #11 from GovTechSG/development
Update and Fix Issue #6 - Failed unit test-cases.
2 parents 964b62c + 938ca4d commit a6c5872

10 files changed

+156
-94
lines changed

.gitignore

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,16 @@
11
# Autosave files
22
*~
3-
# vs project
3+
# Project related
44
.vs/
5+
.idea/
6+
7+
# Output files
8+
ApiUtilLib/bin
9+
ApiUtilLib/obj
10+
11+
# Output Test files
12+
ApiUtilLibTest/bin
13+
ApiUtilLibTest/obj
514

615
# build
716
[Oo]bj/

ApiUtilLib/ApiAuthorization.cs

Lines changed: 63 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,19 @@ public static RSACryptoServiceProvider PrivateKeyFromP12(string certificateFileN
134134
public static string GetL2SignatureFromPEM(string filename, string message, string passPhrase)
135135
{
136136
Logger.LogEnterExit(LoggerBase.Args(filename, "***password***"));
137+
if (String.IsNullOrEmpty(message))
138+
{
139+
Logger.LogError("{0} must not be null or empty.", nameof(message));
140+
141+
throw new ArgumentNullException(nameof(message));
142+
}
143+
144+
if (String.IsNullOrEmpty(filename))
145+
{
146+
Logger.LogError("{0} must not be null or empty.", nameof(filename));
147+
148+
throw new ArgumentNullException(nameof(filename));
149+
}
137150
string result = null;
138151
try
139152
{
@@ -394,52 +407,66 @@ string realm
394407
, string timestamp = null
395408
, string version = "1.0")
396409
{
397-
Logger.LogEnter(LoggerBase.Args(realm, authPrefix, httpMethod, urlPath, appId, secret, formList == null ? null : formList.ToFormData(), privateKey, nonce, timestamp, version));
410+
String nullValueErrMsg = "One or more required parameters are missing!";
411+
try
412+
{
413+
Logger.LogEnter(LoggerBase.Args(realm, authPrefix, httpMethod, urlPath, appId, secret, formList == null ? null : formList.ToFormData(), privateKey, nonce, timestamp, version));
398414

399-
Logger.LogDebug("URL:: {0}", urlPath);
415+
Logger.LogDebug("URL:: {0}", urlPath);
416+
if (String.IsNullOrEmpty(authPrefix))
417+
{
418+
Logger.LogError(nullValueErrMsg);
419+
throw new ArgumentNullException(nameof(authPrefix));
420+
}
400421

401-
authPrefix = authPrefix.ToLower();
402422

403-
// Generate the nonce value
404-
nonce = nonce ?? ApiAuthorization.NewNonce().ToString();
405-
timestamp = timestamp ?? ApiAuthorization.NewTimestamp().ToString();
423+
authPrefix = authPrefix.ToLower();
406424

407-
SignatureMethod signatureMethod = SignatureMethod.HMACSHA256;
408-
if (secret == null)
409-
{
410-
signatureMethod = SignatureMethod.SHA256withRSA;
411-
}
425+
// Generate the nonce value
426+
nonce = nonce ?? ApiAuthorization.NewNonce().ToString();
427+
timestamp = timestamp ?? ApiAuthorization.NewTimestamp().ToString();
428+
429+
SignatureMethod signatureMethod = SignatureMethod.HMACSHA256;
430+
if (secret == null)
431+
{
432+
signatureMethod = SignatureMethod.SHA256withRSA;
433+
}
412434

413-
String baseString = BaseString(authPrefix, signatureMethod
414-
, appId, urlPath, httpMethod
415-
, formList, nonce, timestamp, version);
435+
String baseString = BaseString(authPrefix, signatureMethod
436+
, appId, urlPath, httpMethod
437+
, formList, nonce, timestamp, version);
416438

417-
String base64Token = "";
418-
if (secret != null)
419-
{
420-
base64Token = baseString.L1Signature(secret);
421-
}
422-
else
423-
{
424-
base64Token = baseString.L2Signature(privateKey);
425-
}
439+
String base64Token = "";
440+
if (secret != null)
441+
{
442+
base64Token = baseString.L1Signature(secret);
443+
}
444+
else
445+
{
446+
base64Token = baseString.L2Signature(privateKey);
447+
}
426448

427-
var tokenList = new ApiList();
449+
var tokenList = new ApiList();
428450

429-
tokenList.Add("realm", realm);
430-
tokenList.Add(authPrefix + "_app_id", appId);
431-
tokenList.Add(authPrefix + "_nonce", nonce);
432-
tokenList.Add(authPrefix + "_signature_method", signatureMethod.ToString());
433-
tokenList.Add(authPrefix + "_timestamp", timestamp);
434-
tokenList.Add(authPrefix + "_version", version);
435-
tokenList.Add(authPrefix + "_signature", base64Token);
451+
tokenList.Add("realm", realm);
452+
tokenList.Add(authPrefix + "_app_id", appId);
453+
tokenList.Add(authPrefix + "_nonce", nonce);
454+
tokenList.Add(authPrefix + "_signature_method", signatureMethod.ToString());
455+
tokenList.Add(authPrefix + "_timestamp", timestamp);
456+
tokenList.Add(authPrefix + "_version", version);
457+
tokenList.Add(authPrefix + "_signature", base64Token);
436458

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

439-
Logger.LogDebug("Token :: {0}", authorizationToken);
461+
Logger.LogDebug("Token :: {0}", authorizationToken);
440462

441-
Logger.LogExit(LoggerBase.Args(authorizationToken));
442-
return authorizationToken;
463+
Logger.LogExit(LoggerBase.Args(authorizationToken));
464+
return authorizationToken;
465+
}
466+
catch (Exception ex)
467+
{
468+
throw ex;
469+
}
443470
}
444471

445472
public static int HttpRequest(Uri url, string token = null, ApiList postData = null, HttpMethod httpMethod = HttpMethod.GET, bool ignoreServerCert = false)
@@ -567,7 +594,7 @@ public static void InitiateSSLTrust()
567594
}
568595
catch (Exception ex)
569596
{
570-
Console.WriteLine("{0}", ex);
597+
throw ex;
571598
}
572599
}
573600

ApiUtilLibTest/AuthorizationTokenTest.cs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -39,10 +39,10 @@ static string GetLocalPath(string relativeFileName)
3939
const string nonce = "-5816789581922453013";
4040
const string timestamp = "1502199514462";
4141

42-
//[Test]
42+
[Test]
4343
public void Test_L1_Basic_Test()
4444
{
45-
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=\"";
45+
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=\"";
4646

4747
var authorizationToken = ApiAuthorization.Token(
4848
realm
@@ -55,13 +55,13 @@ public void Test_L1_Basic_Test()
5555
, nonce: nonce
5656
);
5757

58-
Assert.AreEqual(expectedTokenL1, authorizationToken);
58+
Assert.AreEqual(expectedTokenL1, authorizationToken);
5959
}
6060

61-
//[Test]
61+
[Test]
6262
public void Test_L2_Basic_Test()
6363
{
64-
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=\"";
64+
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=\"";
6565

6666
var authorizationToken = ApiAuthorization.Token(
6767
realm

ApiUtilLibTest/BaseService.cs

Lines changed: 40 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,6 @@ internal void downloadFile(string sourceURL, string downloadPath)
8686
}
8787
catch (Exception ex)
8888
{
89-
Console.WriteLine("Exception: " + ex);
9089
throw ex;
9190
}
9291
}
@@ -100,11 +99,9 @@ internal void SetDetaultParams(TestParam paramFile)
10099
apiList = new ApiList();
101100
SetApiList(paramFile.apiParam.formData);
102101
SetApiList(paramFile.apiParam.queryString);
103-
timeStamp = paramFile.apiParam.timestamp;
104-
if (paramFile.apiParam.timestamp.IsNullOrEmpty())
105-
timeStamp = Convert.ToInt32(DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString(), 10).ToString();
102+
timeStamp = paramFile.apiParam.timestamp ?? "%s";
106103
version = paramFile.apiParam.version ?? "1.0";
107-
nonce = paramFile.apiParam.nonce ?? ApiUtilLib.ApiAuthorization.NewNonce();
104+
nonce = paramFile.apiParam.nonce ?? "%s";
108105
authPrefix = paramFile.apiParam.authPrefix;
109106
appId = paramFile.apiParam.appID;
110107
testId = paramFile.id;
@@ -134,32 +131,49 @@ internal void SetApiList(Dictionary<object, object> data = null)
134131
var key = item.Key ?? "";
135132
var value = item.Value ?? "";
136133

137-
if (value.ToString().StartsWith("{", StringComparison.InvariantCulture) && value.ToString().EndsWith("}", StringComparison.InvariantCulture))
138-
value = "";
139-
140-
string[] _subArry = { "" };
141-
string val = null;
142-
if (!value.ToString().IsNullOrEmpty())
134+
String value_s = value.ToString().Trim();
135+
136+
if (!key.ToString().IsNullOrEmpty())
143137
{
144-
val = value.ToString().Trim().RemoveString(new string[] { "[", "]", "\\", "\\ ", " \\", "\"", "\\ ", "\n", " " }).Unescape();
145-
_subArry = val.Split(',');
146-
}
138+
string[] _queryParams = { "" };
139+
string val = null;
140+
141+
if (!value_s.IsNullOrEmpty() && !(value_s.StartsWith("{", StringComparison.InvariantCulture) && value_s.EndsWith("}", StringComparison.InvariantCulture)))
142+
{
143+
144+
val = value_s.RemoveString(new string[] { "\\", "\\ ", " \\", "\"", "\\ ", "\n" }).Unescape();
145+
146+
if (val == "True")
147+
val = "true";
148+
if (val == "False")
149+
val = "false";
150+
if (val.StartsWith("[", StringComparison.InvariantCulture) && val.EndsWith("]", StringComparison.InvariantCulture))
151+
{
152+
153+
string[] _paramValues = { "" };
154+
val = val.RemoveString(new string[] { "[", "]", " " });
155+
_paramValues = val.Split(',');
156+
foreach (var paramvalue in _paramValues)
157+
{
158+
var _paramvalue = paramvalue;
159+
apiList.Add(key.ToString(), _paramvalue.Unescape());
160+
}
161+
162+
}
163+
else
164+
{
165+
apiList.Add(key.ToString(), val);
166+
}
167+
}
168+
else
169+
{
170+
apiList.Add(key.ToString(), val);
171+
}
147172

148-
foreach (var subArry in _subArry)
149-
{
150-
var _val = subArry;
151-
if (_val == "True")
152-
_val = "true";
153-
if (_val == "False")
154-
_val = "false";
155-
156-
if (!key.ToString().IsNullOrEmpty())
157-
apiList.Add(key.ToString(), _val);
158173
}
159174
}
160175
}
161-
}
162-
catch (Exception ex)
176+
}catch (Exception ex)
163177
{
164178
throw ex;
165179
}

ApiUtilLibTest/BaseStringTest.cs

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ public void BaseString_Basic_Test()
3333
Assert.AreEqual(expectedBaseString, baseString);
3434
}
3535

36-
//[Test]
36+
[Test]
3737
public void BaseString_BugTest()
3838
{
3939

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

4545
var url = "https://test.example.com:443/api/v1/rest/level1/in-in/?ap=裕廊坊%20心邻坊";
46-
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";
46+
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";
4747

4848
var baseString = ApiAuthorization.BaseString(
4949
"auth_prefix",
@@ -57,10 +57,6 @@ public void BaseString_BugTest()
5757
"1.0"
5858
);
5959

60-
61-
//Console.WriteLine("\n>>>BaseString :: '{0}'<<<", baseString);
62-
63-
// Console.WriteLine("\n---Lab 3.2---");
6460
Assert.AreEqual(expectedBaseString, baseString);
6561
}
6662

ApiUtilLibTest/CommonExtensions.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ public static string GetCharp(Dictionary<string,string> value)
3737
{
3838
try
3939
{
40-
var result = value.Where(c => c.Key == "charp").FirstOrDefault().Value;
40+
var result = value.Where(c => c.Key == "c#").FirstOrDefault().Value;
4141
if (result==null)
4242
result = value.Where(c => c.Key == "default").FirstOrDefault().Value;
4343

0 commit comments

Comments
 (0)