Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle unencrypted message while getting messages with crypto #198

Merged
merged 7 commits into from
Nov 28, 2023
Merged
Show file tree
Hide file tree
Changes from 6 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
7 changes: 5 additions & 2 deletions src/Api/PubnubApi/EndPoint/Files/DownloadFileOperation.cs
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,8 @@ private void ProcessFileDownloadRequest(Dictionary<string, object> externalQuery
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.ToString());
System.Diagnostics.Debug.WriteLine("{0}\nMessage might be not encrypted, returning as is...", ex.ToString());
outputBytes = item1Bytes;
}
}
PNDownloadFileResult result = new PNDownloadFileResult();
Expand Down Expand Up @@ -241,7 +242,9 @@ private async Task<PNResult<PNDownloadFileResult>> ProcessFileDownloadRequest(Di
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.ToString());
System.Diagnostics.Debug.WriteLine("{0}\nMessage might be not encrypted, returning as is...", ex.ToString());
outputBytes = item1Bytes;
ret.Status = new PNStatus { Error = true, ErrorData = new PNErrorData("Decryption error", ex) };
}
}

Expand Down
13 changes: 12 additions & 1 deletion src/Api/PubnubApi/PubnubCoreBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -724,8 +724,19 @@ private void ResponseToUserCallback<T>(List<object> result, PNOperationType type
}

Announce(status);

LoggingMethod.WriteToLog(
currentLog,
string.Format(
CultureInfo.InvariantCulture,
"Failed to decrypt message on channel {0} in ResponseToUserCallback due to exception={1}.\nMessage might be not encrypted, returning as is...",
currentMessageChannel,
ex
),
currentConfig.LogVerbosity
);
}
object decodeMessage = (decryptMessage == "**DECRYPT ERROR**") ? decryptMessage : jsonLib.DeserializeToObject(decryptMessage);
object decodeMessage = jsonLib.DeserializeToObject((decryptMessage == "**DECRYPT ERROR**") ? payload.ToString() : decryptMessage);

payloadContainer.Add(decodeMessage);
}
Expand Down
6 changes: 4 additions & 2 deletions src/Api/PubnubApi/Security/SecureMessage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,9 @@
{
List<object> returnMessage = new List<object>();

if (config.CryptoModule != null || config.CipherKey.Length > 0)

Check warning on line 31 in src/Api/PubnubApi/Security/SecureMessage.cs

View workflow job for this annotation

GitHub Actions / Acceptance tests

'PNConfiguration.CipherKey' is obsolete: 'CipherKey is deprecated, please use CryptoModule instead.'

Check warning on line 31 in src/Api/PubnubApi/Security/SecureMessage.cs

View workflow job for this annotation

GitHub Actions / Integration and Unit tests

'PNConfiguration.CipherKey' is obsolete: 'CipherKey is deprecated, please use CryptoModule instead.'
{
config.CryptoModule ??= new CryptoModule(new LegacyCryptor(config.CipherKey, config.UseRandomInitializationVector, pubnubLog), null);

Check warning on line 33 in src/Api/PubnubApi/Security/SecureMessage.cs

View workflow job for this annotation

GitHub Actions / Acceptance tests

'PNConfiguration.CipherKey' is obsolete: 'CipherKey is deprecated, please use CryptoModule instead.'

Check warning on line 33 in src/Api/PubnubApi/Security/SecureMessage.cs

View workflow job for this annotation

GitHub Actions / Acceptance tests

'PNConfiguration.UseRandomInitializationVector' is obsolete: 'UseRandomInitializationVector is deprecated, please use CryptoModule instead.'

Check warning on line 33 in src/Api/PubnubApi/Security/SecureMessage.cs

View workflow job for this annotation

GitHub Actions / Integration and Unit tests

'PNConfiguration.CipherKey' is obsolete: 'CipherKey is deprecated, please use CryptoModule instead.'

Check warning on line 33 in src/Api/PubnubApi/Security/SecureMessage.cs

View workflow job for this annotation

GitHub Actions / Integration and Unit tests

'PNConfiguration.UseRandomInitializationVector' is obsolete: 'UseRandomInitializationVector is deprecated, please use CryptoModule instead.'
object[] myObjectArray = (from item in messageList
select item as object).ToArray();
object[] enumerable = myObjectArray[0] as object[];
Expand Down Expand Up @@ -71,7 +71,8 @@

errorCallback.OnResponse(default(T), status);
}
object decodeMessage = (decryptMessage == "**DECRYPT ERROR**") ? decryptMessage : jsonLib.DeserializeToObject(decryptMessage);
pubnubLog.WriteToLog("Failed to decrypt message!\nMessage might be not encrypted, returning as is...");
object decodeMessage = jsonLib.DeserializeToObject((decryptMessage == "**DECRYPT ERROR**") ? element.ToString() : decryptMessage);
receivedMsg.Add(decodeMessage);
}
returnMessage.Add(receivedMsg);
Expand Down Expand Up @@ -127,9 +128,9 @@
Dictionary<string, object> dicDecrypt = new Dictionary<string, object>();
foreach (KeyValuePair<string, object> kvpValue in dicValue)
{
if (kvpValue.Key == "message" && (config.CryptoModule != null || config.CipherKey.Length > 0))

Check warning on line 131 in src/Api/PubnubApi/Security/SecureMessage.cs

View workflow job for this annotation

GitHub Actions / Acceptance tests

'PNConfiguration.CipherKey' is obsolete: 'CipherKey is deprecated, please use CryptoModule instead.'

Check warning on line 131 in src/Api/PubnubApi/Security/SecureMessage.cs

View workflow job for this annotation

GitHub Actions / Integration and Unit tests

'PNConfiguration.CipherKey' is obsolete: 'CipherKey is deprecated, please use CryptoModule instead.'
{
config.CryptoModule ??= new CryptoModule(new LegacyCryptor(config.CipherKey, config.UseRandomInitializationVector, pubnubLog), null);

Check warning on line 133 in src/Api/PubnubApi/Security/SecureMessage.cs

View workflow job for this annotation

GitHub Actions / Acceptance tests

'PNConfiguration.CipherKey' is obsolete: 'CipherKey is deprecated, please use CryptoModule instead.'

Check warning on line 133 in src/Api/PubnubApi/Security/SecureMessage.cs

View workflow job for this annotation

GitHub Actions / Acceptance tests

'PNConfiguration.UseRandomInitializationVector' is obsolete: 'UseRandomInitializationVector is deprecated, please use CryptoModule instead.'

Check warning on line 133 in src/Api/PubnubApi/Security/SecureMessage.cs

View workflow job for this annotation

GitHub Actions / Integration and Unit tests

'PNConfiguration.CipherKey' is obsolete: 'CipherKey is deprecated, please use CryptoModule instead.'

Check warning on line 133 in src/Api/PubnubApi/Security/SecureMessage.cs

View workflow job for this annotation

GitHub Actions / Integration and Unit tests

'PNConfiguration.UseRandomInitializationVector' is obsolete: 'UseRandomInitializationVector is deprecated, please use CryptoModule instead.'
string decryptMessage = "";
try
{
Expand All @@ -154,7 +155,8 @@
errorCallback.OnResponse(default(T), status);
#endregion
}
object decodeMessage = (decryptMessage == "**DECRYPT ERROR**") ? decryptMessage : jsonLib.DeserializeToObject(decryptMessage);
pubnubLog.WriteToLog("Failed to decrypt message!\nMessage might be not encrypted, returning as is...");
object decodeMessage = jsonLib.DeserializeToObject((decryptMessage == "**DECRYPT ERROR**") ? decryptMessage : decryptMessage);
dicDecrypt.Add(kvpValue.Key, decodeMessage);
}
else
Expand Down
131 changes: 130 additions & 1 deletion src/UnitTests/PubnubApi.Tests/EncryptionTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -793,6 +793,135 @@ public void TestPAMv3Signature()
Assert.AreEqual("v2.k80LsDMD-sImA8rCBj-ntRKhZ8mSjHY8Ivngt9W3Yc4", signature);
}

[Test]
async public void TestSubscribeDecryption()
{
bool done = false;
PNConfiguration config = CreateTestConfig();
config.CryptoModule = new CryptoModule(new AesCbcCryptor("enigma"), new List<ICryptor> { new LegacyCryptor("enigma") });

Pubnub sut = new Pubnub(config);

sut.AddListener(new SubscribeCallbackExt(
(pb, message) =>
{
Assert.AreEqual("test", message.Message);
done = true;
},
(pb, presence) => {},
(pb, status) => {}
)
);

sut.Subscribe<string>().Channels(new[] { "test" }).Execute();

Pubnub sender = new Pubnub(CreateTestConfig());

// Rust generated encrypted message
await sender.Publish()
.Channel("test")
.Message("UE5FRAFBQ1JIEALf+E65kseYJwTw2J6BUk9MePHiCcBCS+8ykXLkBIOA")
.ExecuteAsync();

// It will wait until the message is received or unit test timeout is reached
while (!done)
{
await System.Threading.Tasks.Task.Delay(100);
}
}

[Test]
async public void TestSubscribeDecryptionOnNonEncryptedMessage()
{
bool done = false;
PNConfiguration config = CreateTestConfig();
config.CryptoModule = new CryptoModule(new AesCbcCryptor("enigma"), new List<ICryptor> { new LegacyCryptor("enigma") });

Pubnub sut = new Pubnub(config);

sut.AddListener(new SubscribeCallbackExt(
(pb, message) =>
{
Assert.AreEqual("test", message.Message);
done = true;
},
(pb, presence) => {},
(pb, status) => {}
)
);

sut.Subscribe<string>().Channels(new[] { "test" }).Execute();

Pubnub sender = new Pubnub(CreateTestConfig());

// Rust generated encrypted message
await sender.Publish()
.Channel("test")
.Message("test")
.ExecuteAsync();

// It will wait until the message is received or unit test timeout is reached
while (!done)
{
await System.Threading.Tasks.Task.Delay(100);
}
}

[Test]
async public void TestHistoryDecryption()
{
PNConfiguration config = CreateTestConfig();
config.CryptoModule = new CryptoModule(new AesCbcCryptor("enigma"), new List<ICryptor> { new LegacyCryptor("enigma") });

Pubnub sut = new Pubnub(config);

Pubnub sender = new Pubnub(CreateTestConfig());

// Rust generated encrypted message
await sender.Publish()
.Channel("test")
.Message("UE5FRAFBQ1JIEALf+E65kseYJwTw2J6BUk9MePHiCcBCS+8ykXLkBIOA")
.ExecuteAsync();

PNResult<PNHistoryResult> result = await sut.History()
.Channel("test")
.Count(1)
.ExecuteAsync();

Assert.AreEqual("test", result.Result.Messages[0].Entry);
}

[Test]
async public void TestHistoryDecryptionOnNonEncryptedMessage()
{
PNConfiguration config = CreateTestConfig();
config.CryptoModule = new CryptoModule(new AesCbcCryptor("enigma"), new List<ICryptor> { new LegacyCryptor("enigma") });

Pubnub sut = new Pubnub(config);

Pubnub sender = new Pubnub(CreateTestConfig());

// Rust generated encrypted message
await sender.Publish()
.Channel("test")
.Message("test")
.ExecuteAsync();

PNResult<PNHistoryResult> result = await sut.History()
.Channel("test")
.Count(1)
.ExecuteAsync();

Assert.AreEqual("test", result.Result.Messages[0].Entry);
}

private PNConfiguration CreateTestConfig()
{
PNConfiguration config = new PNConfiguration(new UserId("test"));
config.SubscribeKey = "demo";
config.PublishKey = "demo";

return config;
}
}
}
}
Loading