Skip to content

Commit

Permalink
GD-1932: Fix TLS version not updating
Browse files Browse the repository at this point in the history
  • Loading branch information
g1hanna committed Jan 3, 2025
1 parent 2733132 commit 742c617
Show file tree
Hide file tree
Showing 5 changed files with 69 additions and 40 deletions.
3 changes: 1 addition & 2 deletions PluginSalesforce/API/Factory/PushTopicConnectionFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,14 @@ public class PushTopicConnectionFactory : IPushTopicConnectionFactory
{
public PushTopicConnection GetPushTopicConnection(RequestHelper requestHelper, string channel)
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls13;
PushTopicConnection pushTopicConnection = null;

var accessToken = requestHelper.GetToken();
var instanceUrl = requestHelper.GetInstanceUrl();

try
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls13;
var readTimeOut = 120000;
var streamingEndpointURI = "/cometd/52.0";
var options = new Dictionary<string, object>
Expand Down
9 changes: 4 additions & 5 deletions PluginSalesforce/API/Read/GetRecordsForQuery.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web;
using Naveego.Sdk.Plugins;
using Newtonsoft.Json;
Expand All @@ -17,12 +16,12 @@ public static async IAsyncEnumerable<Dictionary<string, object>> GetRecordsForDe
// get records
List<string> allRecordIds = new List<string>();
var loopCount = 0;
var lastId = "";
var previousLastId = "";
var recordCount = 0;

var query = Utility.Utility.GetDefaultQuery(schema);


string lastId;
string previousLastId;
do
{
loopCount++;
Expand Down Expand Up @@ -55,7 +54,7 @@ public static async IAsyncEnumerable<Dictionary<string, object>> GetRecordsForQu
{
response.EnsureSuccessStatusCode();
}
catch (Exception e)
catch
{
var errorBody = await response.Content.ReadAsStringAsync();
throw new Exception(errorBody);
Expand Down
5 changes: 2 additions & 3 deletions PluginSalesforce/Helper/RequestHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Naveego.Sdk.Logging;
using PluginSalesforce.API.Utility;

namespace PluginSalesforce.Helper
{
Expand Down Expand Up @@ -47,7 +46,7 @@ public async Task<HttpResponseMessage> GetAsync(string path)
// add token to the request and execute the request
try
{
var uri = String.Format("{0}/{1}", _baseUrl, path.TrimStart('/'));
var uri = string.Format("{0}/{1}", _baseUrl, path.TrimStart('/'));

var client = _client;
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
Expand Down Expand Up @@ -128,7 +127,7 @@ public async Task<HttpResponseMessage> PutAsync(string path, StringContent json)
// add token to the request and execute the request
try
{
var uri = String.Format("{0}/{1}", _baseUrl, path.TrimStart('/'));
var uri = string.Format("{0}/{1}", _baseUrl, path.TrimStart('/'));

var client = _client;
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
Expand Down
16 changes: 8 additions & 8 deletions PluginSalesforce/Plugin/Plugin.cs
Original file line number Diff line number Diff line change
Expand Up @@ -157,12 +157,12 @@ public override async Task<CompleteOAuthFlowResponse> CompleteOAuthFlow(Complete
InstanceUrl = content.InstanceUrl
});

if (String.IsNullOrEmpty(oAuthState.RefreshToken))
if (string.IsNullOrEmpty(oAuthState.RefreshToken))
{
throw new Exception("Response did not contain a refresh token");
}

if (String.IsNullOrEmpty(content.InstanceUrl))
if (string.IsNullOrEmpty(content.InstanceUrl))
{
throw new Exception("Response did not contain an instance url");
}
Expand Down Expand Up @@ -684,7 +684,7 @@ public override async Task<PrepareWriteResponse> PrepareWrite(PrepareWriteReques
};

// get fields for module
var response = await _client.GetAsync(String.Format("/sobjects/{0}/describe", request.Schema.Id));
var response = await _client.GetAsync(string.Format("/sobjects/{0}/describe", request.Schema.Id));

// for each field in the schema add a new property
var describeResponse =
Expand Down Expand Up @@ -749,7 +749,7 @@ public override async Task WriteStream(IAsyncStreamReader<Record> requestStream,
};
await responseStream.WriteAsync(ack);

if (String.IsNullOrEmpty(task.Result))
if (string.IsNullOrEmpty(task.Result))
{
outCount++;
}
Expand Down Expand Up @@ -820,7 +820,7 @@ private async Task<string> PutRecord(Schema schema, Record record)
if (id != null)
{
// build and send request
var uri = String.Format("/sobjects/{0}/{1}", schema.Id, id);
var uri = string.Format("/sobjects/{0}/{1}", schema.Id, id);

var response = await _client.GetAsync(uri);
response.EnsureSuccessStatusCode();
Expand All @@ -847,7 +847,7 @@ private async Task<string> PutRecord(Schema schema, Record record)
}

// build and send request
uri = String.Format("/sobjects/{0}/{1}", schema.Id, id);
uri = string.Format("/sobjects/{0}/{1}", schema.Id, id);

var patchObj = GetPatchObject(schema, recObj);

Expand All @@ -863,7 +863,7 @@ private async Task<string> PutRecord(Schema schema, Record record)
else
{
// record does not have id and needs to be created
var uri = String.Format("/sobjects/{0}", schema.Id);
var uri = string.Format("/sobjects/{0}", schema.Id);

var patchObj = GetPatchObject(schema, recObj);

Expand Down Expand Up @@ -907,7 +907,7 @@ private async Task<string> DeleteRecord(Schema schema, Record record)
{
// delete record
// build and send request
var uri = String.Format("/sobjects/{0}/{1}", schema.Id, recObj[key.Id]);
var uri = string.Format("/sobjects/{0}/{1}", schema.Id, recObj[key.Id]);

var response = await _client.DeleteAsync(uri);
response.EnsureSuccessStatusCode();
Expand Down
76 changes: 54 additions & 22 deletions PluginSalesforceTest/Plugin/PluginTest.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Grpc.Core;
Expand All @@ -20,19 +20,22 @@ namespace PluginSalesforceTest.Plugin
{
public class PluginTest
{
const string CLIENT_ID = "";
const string CLIENT_SECRET = "";

private ConnectRequest GetConnectSettings()
{
return new ConnectRequest
{
SettingsJson = "",
OauthConfiguration = new OAuthConfiguration
{
ClientId = "client",
ClientSecret = "secret",
ClientId = CLIENT_ID,
ClientSecret = CLIENT_SECRET,
ConfigurationJson = "{}"
},
OauthStateJson =
"{\"RefreshToken\":\"refresh\",\"AuthToken\":\"\",\"Config\":\"{\\\"InstanceUrl\\\":\\\"https://test.salesforce.com\\\"}\"}"
"{\"RefreshToken\":\"refresh\",\"AuthToken\":\"\",\"Config\":\"{\\\"InstanceUrl\\\":\\\"https://login.salesforce.com\\\"}\"}"
};
}

Expand All @@ -41,23 +44,28 @@ private MockHttpMessageHandler GetMockHttpMessageHandler()
var mockHttpHelper = new MockHttpHelper();
var mockHttp = new MockHttpMessageHandler();

mockHttp.When("https://test.salesforce.com/services/oauth2/token")
mockHttp.When(HttpMethod.Post, "https://login.salesforce.com/services/oauth2/token")
.Respond("application/json", mockHttpHelper.Token);

mockHttp.When("https://test.salesforce.com/services/data/v52.0/tabs")
mockHttp.When("https://login.salesforce.com/services/data/v52.0/tabs")
.Respond("application/json", mockHttpHelper.Tabs);

mockHttp.When("https://test.salesforce.com/services/data/v52.0/sobjects/Lead/describe")
mockHttp.When("https://login.salesforce.com/services/data/v52.0/sobjects/Lead/describe")
.Respond("application/json", mockHttpHelper.LeadDescribe);

mockHttp.When("https://test.salesforce.com/services/data/v52.0/sobjects/Account/describe")
mockHttp.When("https://login.salesforce.com/services/data/v52.0/sobjects/Account/describe")
.Respond("application/json", mockHttpHelper.AccountDescribe);

mockHttp.When("https://test.salesforce.com/services/data/v52.0/query?q=select+Id,Name,LastModifiedDate+from+Account")
mockHttp.When("https://login.salesforce.com/services/data/v52.0/query?q=select+Id,Name,LastModifiedDate+from+Account")
.Respond("application/json", mockHttpHelper.AccountQuery);

mockHttp.When("https://login.salesforce.com/services/data/v52.0/query?q=select+fields(all)+from+Account+order+by+id+asc+nulls+last+limit+200+")
.Respond("application/json", mockHttpHelper.AccountQuery);

mockHttp.When("https://test.salesforce.com/services/data/v52.0/sobjects/Account/1")
mockHttp.When("https://login.salesforce.com/services/data/v52.0/sobjects/Account/1")
.Respond("application/json", mockHttpHelper.AccountById);

// mock needed: https://login.salesforce.com/cometd/52.0

return mockHttp;
}
Expand All @@ -84,8 +92,8 @@ public async Task BeginOAuthFlowTest()
{
Configuration = new OAuthConfiguration
{
ClientId = "client",
ClientSecret = "secret",
ClientId = CLIENT_ID,
ClientSecret = CLIENT_SECRET,
ConfigurationJson = "{}"
},
RedirectUrl = "http://test.com"
Expand All @@ -97,8 +105,8 @@ public async Task BeginOAuthFlowTest()
var prompt = "consent";
var display = "popup";

var authUrl = String.Format(
"https://test.salesforce.com/services/oauth2/authorize?client_id={0}&response_type={1}&redirect_uri={2}&prompt={3}&display={4}",
var authUrl = string.Format(
"https://login.salesforce.com/services/oauth2/authorize?client_id={0}&response_type={1}&redirect_uri={2}&prompt={3}&display={4}",
clientId,
responseType,
redirectUrl,
Expand Down Expand Up @@ -139,8 +147,8 @@ public async Task CompleteOAuthFlowTest()
{
Configuration = new OAuthConfiguration
{
ClientId = "client",
ClientSecret = "secret",
ClientId = CLIENT_ID,
ClientSecret = CLIENT_SECRET,
ConfigurationJson = "{}"
},
RedirectUrl = "http://test.com?code=authcode",
Expand Down Expand Up @@ -317,13 +325,16 @@ public async Task DiscoverSchemasRefreshTest()
await channel.ShutdownAsync();
await server.ShutdownAsync();
}
[Fact]

[Fact]
public async Task ReadStreamRealTimeTest()
{
// setup
var mockHttp = GetMockHttpMessageHandler();

Server server = new Server
{
Services = {Publisher.BindService(new PluginSalesforce.Plugin.Plugin())},
Services = {Publisher.BindService(new PluginSalesforce.Plugin.Plugin(mockHttp.ToHttpClient()))},
Ports = {new ServerPort("localhost", 0, ServerCredentials.Insecure)}
};
server.Start();
Expand All @@ -334,7 +345,7 @@ public async Task ReadStreamRealTimeTest()
var client = new Publisher.PublisherClient(channel);

var schema = new Schema();
schema.Query = "SELECT Id, Name from Lead";
schema.Query = "select Id,Name,LastModifiedDate from Account";

var connectRequest = GetConnectSettings();

Expand All @@ -360,6 +371,16 @@ public async Task ReadStreamRealTimeTest()
var records = new List<Record>();
try
{
var configureRequest = new ConfigureRequest
{
TemporaryDirectory = "../../../Temp",
PermanentDirectory = "../../../Perm",
LogDirectory = "../../../Logs",
DataVersions = new DataVersions(),
LogLevel = LogLevel.Debug
};
client.Configure(configureRequest);

client.Connect(connectRequest);
var schemasResponse = client.DiscoverSchemas(schemaRequest);
request.Schema = schemasResponse.Schemas[0];
Expand All @@ -369,22 +390,21 @@ public async Task ReadStreamRealTimeTest()
var response = client.ReadStream(request, null, null, cancellationToken.Token);
var responseStream = response.ResponseStream;


while (await responseStream.MoveNext())
{
records.Add(responseStream.Current);
}
}
catch (Exception e)
{
Assert.Equal("Status(StatusCode=Cancelled, Detail=\"Cancelled\")", e.Message);
Assert.Equal("Status(StatusCode=\"Cancelled\", Detail=\"Cancelled\")", e.Message);
}


// assert
Assert.Equal(3, records.Count);

var record = JsonConvert.DeserializeObject<Dictionary<string, object>>(records[0].DataJson);
// var record = JsonConvert.DeserializeObject<Dictionary<string, object>>(records[0].DataJson);
// Assert.Equal("~", record["tilde"]);

// cleanup
Expand Down Expand Up @@ -560,6 +580,12 @@ public async Task PrepareWriteTest()

var request = new PrepareWriteRequest()
{
DataVersions = new DataVersions {
JobId = "test",
ShapeId = "test-shape",
JobDataVersion = 1,
ShapeDataVersion = 1,
},
Schema = new Schema
{
Id = "Account",
Expand Down Expand Up @@ -627,6 +653,12 @@ public async Task WriteStreamTest()

var prepareRequest = new PrepareWriteRequest()
{
DataVersions = new DataVersions {
JobId = "test-write",
ShapeId = "test-write-shape",
JobDataVersion = 1,
ShapeDataVersion = 1,
},
Schema = new Schema
{
Id = "Account",
Expand Down

0 comments on commit 742c617

Please sign in to comment.