Skip to content

Commit 872d29e

Browse files
authored
SessionsPythonPlugin bug fix (#14374)
### Motivation and Context <!-- Thank you for your contribution to the semantic-kernel repo! Please help reviewers and future users, providing the following information: 1. Why is this change required? 2. What problem does it solve? 3. What scenario does it contribute to? 4. If it fixes an open issue, please link to the issue here. --> ### Description <!-- Describe your changes, the overall approach, the underlying design. These notes will help understanding how your code works. Thanks! --> ### Contribution Checklist <!-- Before submitting this PR, please make sure: --> - [ ] The code builds clean without any errors or warnings - [ ] The PR follows the [SK Contribution Guidelines](https://github.com/microsoft/semantic-kernel/blob/main/CONTRIBUTING.md) and the [pre-submission formatting script](https://github.com/microsoft/semantic-kernel/blob/main/CONTRIBUTING.md#development-scripts) raises no violations - [ ] All unit tests pass, and I have added new tests where possible - [ ] I didn't break anyone 😄
1 parent ebc2ef9 commit 872d29e

6 files changed

Lines changed: 87 additions & 16 deletions

File tree

‎dotnet/samples/Demos/CodeInterpreterPlugin/Program.cs‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -54,9 +54,13 @@ async Task<string> TokenProvider(CancellationToken cancellationToken)
5454
return cachedToken;
5555
}
5656

57+
var sessionEndpoint = new Uri(endpoint);
5758
var settings = new SessionsPythonSettings(
5859
sessionId: Guid.NewGuid().ToString(),
59-
endpoint: new Uri(endpoint));
60+
endpoint: sessionEndpoint)
61+
{
62+
AllowedDomains = [sessionEndpoint.Host]
63+
};
6064

6165
// Uncomment the following lines to enable file upload operations (disabled by default for security)
6266
// settings.EnableDangerousFileUploads = true;
@@ -73,7 +77,9 @@ async Task<string> TokenProvider(CancellationToken cancellationToken)
7377

7478
// Change the log level to Trace to see more detailed logs
7579
builder.Services.AddLogging(loggingBuilder => loggingBuilder.AddConsole().SetMinimumLevel(LogLevel.Information));
76-
builder.Services.AddHttpClient();
80+
builder.Services
81+
.AddHttpClient(string.Empty)
82+
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false });
7783
builder.Services.AddSingleton((sp)
7884
=> new SessionsPythonPlugin(
7985
settings,

‎dotnet/src/IntegrationTests/Plugins/Core/SessionsPythonPluginTests.cs‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@ public SessionsPythonPluginTests()
4545
{
4646
CodeExecutionType = SessionsPythonSettings.CodeExecutionTypeSetting.Synchronous,
4747
CodeInputType = SessionsPythonSettings.CodeInputTypeSetting.Inline,
48+
AllowedDomains = [new Uri(_spConfiguration.Endpoint).Host],
4849
// Enable file operations for integration tests
4950
EnableDangerousFileUploads = true,
5051
AllowedUploadDirectories = new[] { Path.GetFullPath("TestData") },
@@ -186,17 +187,21 @@ public void Dispose()
186187
private sealed class HttpClientFactory : IHttpClientFactory, IDisposable
187188
{
188189
private readonly List<HttpClient> _httpClients = [];
190+
private readonly List<HttpClientHandler> _httpClientHandlers = [];
189191

190192
public HttpClient CreateClient(string name)
191193
{
192-
var client = new HttpClient();
194+
var handler = new HttpClientHandler { AllowAutoRedirect = false };
195+
var client = new HttpClient(handler, disposeHandler: false);
196+
this._httpClientHandlers.Add(handler);
193197
this._httpClients.Add(client);
194198
return client;
195199
}
196200

197201
public void Dispose()
198202
{
199203
this._httpClients.ForEach(client => client.Dispose());
204+
this._httpClientHandlers.ForEach(handler => handler.Dispose());
200205
}
201206
}
202207
}

‎dotnet/src/Plugins/Plugins.Core/CodeInterpreter/SessionsPythonPlugin.cs‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,10 @@ public sealed partial class SessionsPythonPlugin
3737
/// <param name="httpClientFactory">The HTTP client factory.</param>
3838
/// <param name="authTokenProvider">Optional provider for auth token generation.</param>
3939
/// <param name="loggerFactory">The logger factory.</param>
40+
/// <remarks>
41+
/// The <paramref name="httpClientFactory"/> must create clients with automatic redirects disabled
42+
/// to prevent redirects from bypassing <see cref="SessionsPythonSettings.AllowedDomains"/>.
43+
/// </remarks>
4044
public SessionsPythonPlugin(
4145
SessionsPythonSettings settings,
4246
IHttpClientFactory httpClientFactory,
@@ -271,11 +275,11 @@ private async Task<HttpResponseMessage> SendAsync(HttpClient httpClient, HttpMet
271275

272276
var uri = new Uri(this._poolManagementEndpoint, pathWithQueryString);
273277

274-
// If a list of allowed domains has been provided, the host of the provided
275-
// uri is checked to verify it is in the allowed domain list.
276-
if (!this._settings.AllowedDomains?.Contains(uri.Host) ?? false)
278+
// Deny requests unless the endpoint host is explicitly allowed.
279+
if (this._settings.AllowedDomains?.Contains(uri.Host, StringComparer.OrdinalIgnoreCase) != true)
277280
{
278-
throw new InvalidOperationException("Sending requests to the provided location is not allowed.");
281+
throw new InvalidOperationException(
282+
$"Sending requests to host '{uri.Host}' is not allowed. Add the host to {nameof(SessionsPythonSettings.AllowedDomains)}.");
279283
}
280284

281285
using var request = new HttpRequestMessage(method, uri)

‎dotnet/src/Plugins/Plugins.Core/CodeInterpreter/SessionsPythonSettings.cs‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,8 +25,13 @@ public class SessionsPythonSettings
2525
public Uri Endpoint { get; set; }
2626

2727
/// <summary>
28-
/// List of allowed domains to download from.
28+
/// Gets or sets the domains to which the plugin may send requests.
29+
/// If <c>null</c> or empty, all requests are denied.
2930
/// </summary>
31+
/// <remarks>
32+
/// Configure the HTTP client factory used by <see cref="SessionsPythonPlugin"/> with automatic redirects disabled
33+
/// to prevent redirects from bypassing this allowlist.
34+
/// </remarks>
3035
public IEnumerable<string>? AllowedDomains { get; set; }
3136

3237
/// <summary>

‎dotnet/src/Plugins/Plugins.UnitTests/Core/SessionsPythonPluginTests.cs‎

Lines changed: 57 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,8 @@ public sealed class SessionsPythonPluginTests : IDisposable
3333
endpoint: new Uri("http://localhost:8888"))
3434
{
3535
CodeExecutionType = SessionsPythonSettings.CodeExecutionTypeSetting.Synchronous,
36-
CodeInputType = SessionsPythonSettings.CodeInputTypeSetting.Inline
36+
CodeInputType = SessionsPythonSettings.CodeInputTypeSetting.Inline,
37+
AllowedDomains = ["localhost"]
3738
};
3839

3940
private readonly SessionsPythonSettings _settingsWithFileOperationsEnabled;
@@ -57,6 +58,7 @@ public SessionsPythonPluginTests()
5758
{
5859
CodeExecutionType = SessionsPythonSettings.CodeExecutionTypeSetting.Synchronous,
5960
CodeInputType = SessionsPythonSettings.CodeInputTypeSetting.Inline,
61+
AllowedDomains = ["localhost"],
6062
EnableDangerousFileUploads = true,
6163
AllowedUploadDirectories = new[] { Path.GetDirectoryName(Path.GetFullPath(FileTestDataFilePath))! },
6264
AllowedDownloadDirectories = new[] { Path.GetDirectoryName(Path.GetFullPath(FileTestDataFilePath))! }
@@ -335,6 +337,7 @@ public async Task ItShouldDownloadFileSavingInDiskAsync()
335337
[InlineData("prod.fake-test-host.io", "https://prod.fake-test-host.io/subscriptions/123/rg/456/sps/test-pool", true)]
336338
[InlineData("www.fake-test-host.io", "https://www.fake-test-host.io/subscriptions/123/rg/456/sps/test-pool", true)]
337339
[InlineData("www.prod.fake-test-host.io", "https://www.prod.fake-test-host.io/subscriptions/123/rg/456/sps/test-pool", true)]
340+
[InlineData("FAKE-TEST-HOST.IO", "https://fake-test-host.io/subscriptions/123/rg/456/sps/test-pool", true)]
338341
[InlineData("fake-test-host.io", "https://fake-test-host-1.io/subscriptions/123/rg/456/sps/test-pool", false)]
339342
[InlineData("fake-test-host.io", "https://www.fake-test-host.io/subscriptions/123/rg/456/sps/test-pool", false)]
340343
[InlineData("www.fake-test-host.io", "https://fake-test-host.io/subscriptions/123/rg/456/sps/test-pool", false)]
@@ -351,17 +354,63 @@ public async Task ItShouldRespectAllowedDomainsAsync(string allowedDomain, strin
351354

352355
var sut = new SessionsPythonPlugin(this._defaultSettings, this._httpClientFactory);
353356

354-
// Act
355-
#pragma warning disable CA1031 // Do not catch general exception types
356-
try
357+
// Act and assert
358+
if (isAllowed)
357359
{
358360
await sut.ListFilesAsync();
359361
}
360-
catch when (!isAllowed)
362+
else
361363
{
362-
// Ignore exception if the endpoint is not allowed since we expect it
364+
await Assert.ThrowsAsync<InvalidOperationException>(() => sut.ListFilesAsync());
363365
}
364-
#pragma warning restore CA1031 // Do not catch general exception types
366+
}
367+
368+
[Fact]
369+
public async Task ItShouldDenyRequestsWhenAllowedDomainsIsNullAsync()
370+
{
371+
// Arrange
372+
this._defaultSettings.AllowedDomains = null;
373+
this._defaultSettings.Endpoint = new Uri("http://169.254.169.254/metadata/instance");
374+
var sut = new SessionsPythonPlugin(this._defaultSettings, this._httpClientFactory);
375+
376+
// Act and assert
377+
await Assert.ThrowsAsync<InvalidOperationException>(() => sut.ListFilesAsync());
378+
}
379+
380+
[Fact]
381+
public async Task ItShouldDenyRequestsWhenAllowedDomainsIsEmptyAsync()
382+
{
383+
// Arrange
384+
this._defaultSettings.AllowedDomains = [];
385+
this._defaultSettings.Endpoint = new Uri("http://169.254.169.254/metadata/instance");
386+
var sut = new SessionsPythonPlugin(this._defaultSettings, this._httpClientFactory);
387+
388+
// Act and assert
389+
await Assert.ThrowsAsync<InvalidOperationException>(() => sut.ListFilesAsync());
390+
}
391+
392+
[Fact]
393+
public async Task ItShouldRejectRedirectResponseFromNonRedirectingClientAsync()
394+
{
395+
// Arrange
396+
await using var server = new RedirectLoopbackServer("metadata/instance", "application/json", []);
397+
using var httpClientHandler = new HttpClientHandler { AllowAutoRedirect = false };
398+
using var nonRedirectingClient = new HttpClient(httpClientHandler);
399+
var httpClientFactoryMock = new Mock<IHttpClientFactory>();
400+
httpClientFactoryMock.Setup(f => f.CreateClient(It.IsAny<string>())).Returns(nonRedirectingClient);
401+
var settings = new SessionsPythonSettings(
402+
sessionId: Guid.NewGuid().ToString(),
403+
endpoint: new Uri(server.BaseUri, "start"))
404+
{
405+
AllowedDomains = [server.BaseUri.Host],
406+
CodeExecutionType = SessionsPythonSettings.CodeExecutionTypeSetting.Synchronous,
407+
CodeInputType = SessionsPythonSettings.CodeInputTypeSetting.Inline
408+
};
409+
var sut = new SessionsPythonPlugin(settings, httpClientFactoryMock.Object);
410+
411+
// Act and assert
412+
await Assert.ThrowsAsync<HttpOperationException>(() => sut.ListFilesAsync());
413+
Assert.False(server.RedirectTargetContacted, "The redirect target should not have been contacted.");
365414
}
366415

367416
[Fact]
@@ -539,6 +588,7 @@ public async Task ItShouldAllowDownloadDirectlyInsideAllowedDirectoryAsync()
539588
sessionId: Guid.NewGuid().ToString(),
540589
endpoint: new Uri("http://localhost:8888"))
541590
{
591+
AllowedDomains = ["localhost"],
542592
AllowedDownloadDirectories = new[] { tempDir }
543593
};
544594

‎dotnet/src/Plugins/Plugins.UnitTests/Support/RedirectLoopbackServer.cs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,8 @@ private async Task HandleRequestAsync(TcpClient client, CancellationToken cancel
106106
while (!string.IsNullOrEmpty(header));
107107

108108
var requestTarget = requestLine?.Split(' ')[1];
109-
if (requestTarget == "/start")
109+
var requestPath = requestTarget?.Split('?')[0];
110+
if (!string.Equals(requestPath, this._redirectTargetPath, StringComparison.Ordinal))
110111
{
111112
var response = $"HTTP/1.1 302 Found\r\nLocation: {new Uri(this.BaseUri, this._redirectTargetPath.TrimStart('/'))}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n";
112113
await stream.WriteAsync(Encoding.ASCII.GetBytes(response), cancellationToken).ConfigureAwait(false);

0 commit comments

Comments
 (0)