Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
38 changes: 38 additions & 0 deletions src/Stripe.net/Infrastructure/Public/SystemNetHttpClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ namespace Stripe
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
Expand Down Expand Up @@ -133,6 +135,9 @@ public SystemNetHttpClient(
/// </summary>
public static TimeSpan MinNetworkRetriesDelay => TimeSpan.FromMilliseconds(500);

/// <summary>Gets or sets the cached source hash. Internal for testing.</summary>
Comment thread
xavdid marked this conversation as resolved.
Outdated
internal static string SourceHash { get; set; } = ComputeSourceHash();

/// <summary>
/// Gets whether telemetry was enabled for this client.
/// </summary>
Expand Down Expand Up @@ -222,6 +227,35 @@ internal static string DetectAIAgent(Func<string, string> getEnv)
return string.Empty;
}

internal static string ComputeSourceHash()
{
try
{
var parts = new System.Collections.Generic.List<string>
{
System.Runtime.InteropServices.RuntimeInformation.OSDescription,
};
try
{
parts.Add(Environment.MachineName);
}
catch
{
}

var inputBytes = Encoding.UTF8.GetBytes(string.Join(" ", parts));
using (var md5 = MD5.Create())
{
var hashBytes = md5.ComputeHash(inputBytes);
return BitConverter.ToString(hashBytes).Replace("-", string.Empty).ToLowerInvariant();
}
}
catch
{
return string.Empty;
}
}

private async Task<(HttpResponseMessage responseMessage, int retries)> SendHttpRequest(
StripeRequest request,
CancellationToken cancellationToken)
Expand Down Expand Up @@ -297,6 +331,10 @@ private string BuildStripeClientUserAgentString()
{ "lang", ".net" },
{ "stripe_net_target_framework", StripeNetTargetFramework },
};
if (!string.IsNullOrEmpty(SourceHash))
{
values["source"] = SourceHash;
Comment thread
xavdid marked this conversation as resolved.
}

// The following values are in try/catch blocks on the off chance that the
// RuntimeInformation methods fail in an unexpected way. This should ~never happen, but
Expand Down
110 changes: 110 additions & 0 deletions src/StripeTests/Infrastructure/Public/SystemNetHttpClientTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,96 @@ public void CanInspectEnableTelemetry()
Assert.True(client.EnableTelemetry);
}

[Fact]
public void SourceHashIsHexString()
{
var hash = SystemNetHttpClient.ComputeSourceHash();

// MD5 produces 16 bytes → 32 hex characters
Assert.NotNull(hash);
Assert.Equal(32, hash.Length);
Assert.Matches("^[0-9a-f]{32}$", hash);
}

[Fact]
public void SourceHashIsDeterministic()
{
var hash1 = SystemNetHttpClient.ComputeSourceHash();
var hash2 = SystemNetHttpClient.ComputeSourceHash();

Assert.Equal(hash1, hash2);
}

[Fact]
public async Task SourceHashIncludedInUserAgentHeader()
{
var responseMessage = new HttpResponseMessage(HttpStatusCode.OK);
responseMessage.Content = new StringContent("Hello world!");
this.MockHttpClientFixture.MockHandler.Protected()
.Setup<Task<HttpResponseMessage>>(
"SendAsync",
ItExpr.IsAny<HttpRequestMessage>(),
ItExpr.IsAny<CancellationToken>())
.Returns(Task.FromResult(responseMessage));

var client = new SystemNetHttpClient(
httpClient: new HttpClient(this.MockHttpClientFixture.MockHandler.Object));
var request = new StripeRequest(
this.StripeClient,
HttpMethod.Post,
"/foo",
null,
null);
await client.MakeRequestAsync(request);

this.MockHttpClientFixture.MockHandler.Protected()
.Verify(
"SendAsync",
Times.Once(),
ItExpr.Is<HttpRequestMessage>(m => this.VerifySourceHeader(m.Headers)),
ItExpr.IsAny<CancellationToken>());
}

[Fact]
public async Task SourceHashAbsentFromUserAgentWhenEmpty()
{
var savedHash = SystemNetHttpClient.SourceHash;
try
{
SystemNetHttpClient.SourceHash = string.Empty;

var responseMessage = new HttpResponseMessage(HttpStatusCode.OK);
responseMessage.Content = new StringContent("Hello world!");
this.MockHttpClientFixture.MockHandler.Protected()
.Setup<Task<HttpResponseMessage>>(
"SendAsync",
ItExpr.IsAny<HttpRequestMessage>(),
ItExpr.IsAny<CancellationToken>())
.Returns(Task.FromResult(responseMessage));

var client = new SystemNetHttpClient(
httpClient: new HttpClient(this.MockHttpClientFixture.MockHandler.Object));
var request = new StripeRequest(
this.StripeClient,
HttpMethod.Post,
"/foo",
null,
null);
await client.MakeRequestAsync(request);

this.MockHttpClientFixture.MockHandler.Protected()
.Verify(
"SendAsync",
Times.Once(),
ItExpr.Is<HttpRequestMessage>(m => this.VerifyNoSourceHeader(m.Headers)),
ItExpr.IsAny<CancellationToken>());
}
finally
{
SystemNetHttpClient.SourceHash = savedHash;
}
}

[Fact]
public void TestDetectAIAgent()
{
Expand Down Expand Up @@ -272,5 +362,25 @@ private bool VerifyAIAgentHeaders(HttpRequestHeaders headers)

return true;
}

private bool VerifySourceHeader(HttpRequestHeaders headers)
{
var userAgentJson = JObject.Parse(headers.GetValues("X-Stripe-Client-User-Agent").First());
var source = userAgentJson.Value<string>("source");

Assert.NotNull(source);
Assert.Matches("^[0-9a-f]{32}$", source);

return true;
}

private bool VerifyNoSourceHeader(HttpRequestHeaders headers)
{
var userAgentJson = JObject.Parse(headers.GetValues("X-Stripe-Client-User-Agent").First());

Assert.Null(userAgentJson["source"]);

return true;
}
}
}
Loading