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

In Auto setup, when IsUninitialized, response http status code 503 #16834

Open
wants to merge 30 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 9 commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
5c0cfbe
In Auto setup, when IsUninitialized, response http status code 409
infofromca Oct 4, 2024
cbb43d2
Remove ILogger
infofromca Oct 4, 2024
1573e53
Update src/OrchardCore.Modules/OrchardCore.AutoSetup/Services/IAutoSe…
infofromca Oct 4, 2024
ff715ae
Update src/OrchardCore.Modules/OrchardCore.AutoSetup/Services/AutoSet…
infofromca Oct 4, 2024
5ffc4aa
Update src/OrchardCore.Modules/OrchardCore.AutoSetup/Services/AutoSet…
infofromca Oct 4, 2024
c02123c
Update src/OrchardCore.Modules/OrchardCore.AutoSetup/Services/AutoSet…
infofromca Oct 4, 2024
281daa4
Update src/OrchardCore.Modules/OrchardCore.AutoSetup/Services/AutoSet…
infofromca Oct 4, 2024
511dc12
Update src/OrchardCore.Modules/OrchardCore.AutoSetup/Services/AutoSet…
infofromca Oct 4, 2024
7a51f44
Move the docs to the interface
infofromca Oct 4, 2024
1fbc8c6
Update src/OrchardCore.Modules/OrchardCore.AutoSetup/Services/IAutoSe…
infofromca Oct 4, 2024
6f99df3
Update src/OrchardCore.Modules/OrchardCore.AutoSetup/Services/AutoSet…
infofromca Oct 4, 2024
9c25005
change to 503
infofromca Oct 4, 2024
2d52d80
Consider the failure situation
infofromca Oct 5, 2024
37aaf73
Merge branch 'main' into 409
hishamco Oct 5, 2024
1cf54b3
Show the error message to the user
infofromca Oct 11, 2024
23333d7
Test -- InvokeAsync_InitializedShell_SkipsSetup
infofromca Oct 12, 2024
4f665ce
InvokeAsync_FailedSetup_ReturnsServiceUnavailable
infofromca Oct 12, 2024
4255865
InvokeAsync_FailedLockAcquisition_ThrowsTimeoutException
infofromca Oct 12, 2024
ed75f46
InvokeAsync_UnInitializedShell_PerformsSetup
infofromca Oct 12, 2024
889565e
Clean
infofromca Oct 12, 2024
b039be0
Clean
infofromca Oct 12, 2024
13ba574
Correct DI scope for IAutoSetupService
infofromca Oct 29, 2024
debdf12
Won't stop other Middlewares after success
infofromca Oct 29, 2024
9d0902f
Code styling
Piedone Oct 29, 2024
29a8a10
Shouldn't write error messages to the response directly
infofromca Oct 30, 2024
4b5ae4b
Merge branch 'main' into 409
hishamco Nov 2, 2024
3c806ab
Update test/OrchardCore.Tests/Modules/OrchardCore.AutoSetup/AutoSetup…
infofromca Nov 2, 2024
30cf024
Update test/OrchardCore.Tests/Modules/OrchardCore.AutoSetup/AutoSetup…
infofromca Nov 2, 2024
d02b9e1
Update test/OrchardCore.Tests/Modules/OrchardCore.AutoSetup/AutoSetup…
infofromca Nov 2, 2024
703a622
Update src/OrchardCore.Modules/OrchardCore.AutoSetup/Services/AutoSet…
infofromca Nov 2, 2024
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
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System.Text;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
Expand Down Expand Up @@ -112,20 +113,23 @@ public async Task InvokeAsync(HttpContext httpContext)
}

// Check if the tenant was installed by another instance.
using var settings = (await _shellSettingsManager
.LoadSettingsAsync(_shellSettings.Name))
.AsDisposable();
using var settings = await _shellSettingsManager.LoadSettingsAsync(_shellSettings.Name);

if (!settings.IsUninitialized())
if (settings != null)
{
await _shellHost.ReloadShellContextAsync(_shellSettings, eventSource: false);
httpContext.Response.StatusCode = 503;

return;
settings.AsDisposable();
if (!settings.IsUninitialized())
{
await _shellHost.ReloadShellContextAsync(_shellSettings, eventSource: false);
httpContext.Response.StatusCode = StatusCodes.Status503ServiceUnavailable;
await httpContext.Response.WriteAsync("The requested tenant is not initialized.");
return;
}
}

var autoSetupService = httpContext.RequestServices.GetRequiredService<IAutoSetupService>();
if (await autoSetupService.SetupTenantAsync(_setupOptions, _shellSettings))
(var setupContext, var isSuccess) = await autoSetupService.SetupTenantAsync(_setupOptions, _shellSettings);
if (isSuccess)
{
if (_setupOptions.IsDefault)
{
Expand All @@ -140,13 +144,17 @@ public async Task InvokeAsync(HttpContext httpContext)
}

httpContext.Response.Redirect(pathBase);

return;
}
else
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This would prevent the error message from being displayed to the user. Like server-side validation or database creation error.

Even if you still decide to keep 503 as the code.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

{
httpContext.Response.StatusCode = 503;
httpContext.Response.StatusCode = StatusCodes.Status503ServiceUnavailable;
var stringBuilder = new StringBuilder();
foreach (var error in setupContext.Errors)
{
stringBuilder.AppendLine($"{error.Key} : '{error.Value}'");
}

await httpContext.Response.WriteAsync($"The AutoSetup failed installing the site '{_setupOptions.SiteName}' with errors: {stringBuilder}.");
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You shouldn't write error messages to the response directly. For instance here the SiteName is user input and could contain XSS. I believe it was only logged before. If we want to keep doing it then we don't need the tuple as a return type.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@sebastienros : Committed new one of shouldn't write error messages to the response directly

return;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ ILogger<AutoSetupService> logger
_logger = logger;
}

public async Task<bool> SetupTenantAsync(TenantSetupOptions setupOptions, ShellSettings shellSettings)
public async Task<(SetupContext, bool)> SetupTenantAsync(TenantSetupOptions setupOptions, ShellSettings shellSettings)
{
var setupContext = await GetSetupContextAsync(setupOptions, shellSettings);

Expand All @@ -39,7 +39,7 @@ public async Task<bool> SetupTenantAsync(TenantSetupOptions setupOptions, ShellS
{
_logger.LogInformation("The AutoSetup successfully provisioned the site '{SiteName}'.", setupOptions.SiteName);

return true;
return (setupContext,true);
Piedone marked this conversation as resolved.
Show resolved Hide resolved
}

var stringBuilder = new StringBuilder();
Expand All @@ -50,7 +50,7 @@ public async Task<bool> SetupTenantAsync(TenantSetupOptions setupOptions, ShellS

_logger.LogError("The AutoSetup failed installing the site '{SiteName}' with errors: {Errors}.", setupOptions.SiteName, stringBuilder);

return false;
return (setupContext, false);
}

public async Task<ShellSettings> CreateTenantSettingsAsync(TenantSetupOptions setupOptions)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,5 +29,5 @@ public interface IAutoSetupService
/// <returns>
/// Returns <see langword="true" /> if successfully setup.
/// </returns>
Task<bool> SetupTenantAsync(TenantSetupOptions setupOptions, ShellSettings shellSettings);
Task<(SetupContext, bool)> SetupTenantAsync(TenantSetupOptions setupOptions, ShellSettings shellSettings);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
using OrchardCore.AutoSetup;
using OrchardCore.AutoSetup.Options;
using OrchardCore.AutoSetup.Services;
using OrchardCore.Environment.Shell;
using OrchardCore.Environment.Shell.Models;
using OrchardCore.Locking;
using OrchardCore.Locking.Distributed;
using OrchardCore.Setup.Services;

namespace OrchardCore.Tests.Modules.OrchardCore.AutoSetup;

public class AutoSetupMiddlewareTests
{
private readonly Mock<IShellHost> _mockShellHost;
private readonly ShellSettings _shellSettings;
private readonly Mock<IShellSettingsManager> _mockShellSettingsManager;
private readonly Mock<IDistributedLock> _mockDistributedLock;
private readonly Mock<IOptions<AutoSetupOptions>> _mockOptions;
private readonly Mock<IAutoSetupService> _mockAutoSetupService;

public AutoSetupMiddlewareTests()
{
_shellSettings = new ShellSettings();
_shellSettings.AsDefaultShell();
_mockShellHost = new Mock<IShellHost>();
_mockShellSettingsManager = new Mock<IShellSettingsManager>();
_mockDistributedLock = new Mock<IDistributedLock>();
_mockOptions = new Mock<IOptions<AutoSetupOptions>>();
_mockAutoSetupService = new Mock<IAutoSetupService>();

_mockOptions.Setup(o => o.Value).Returns(new AutoSetupOptions
{
LockOptions = new LockOptions(),
Tenants = new List<TenantSetupOptions>
{
new TenantSetupOptions { ShellName = ShellSettings.DefaultShellName }
}
infofromca marked this conversation as resolved.
Show resolved Hide resolved
});
}

[Fact]
public async Task InvokeAsync_InitializedShell_SkipsSetup()
{
// Arrange
_shellSettings.State = TenantState.Running;

var httpContext = new DefaultHttpContext();
var nextCalled = false;

infofromca marked this conversation as resolved.
Show resolved Hide resolved
var middleware = new AutoSetupMiddleware(
next: (innerHttpContext) => { nextCalled = true; return Task.CompletedTask; },
infofromca marked this conversation as resolved.
Show resolved Hide resolved
_mockShellHost.Object,
_shellSettings,
_mockShellSettingsManager.Object,
_mockDistributedLock.Object,
_mockOptions.Object);

// Act
await middleware.InvokeAsync(httpContext);

// Assert
Assert.True(nextCalled);
_mockAutoSetupService.Verify(s => s.SetupTenantAsync(It.IsAny<TenantSetupOptions>(), It.IsAny<ShellSettings>()), Times.Never);
}

[Fact]
public async Task InvokeAsync_FailedSetup_ReturnsServiceUnavailable()
{
// Arrange
_shellSettings.State = TenantState.Uninitialized;

SetupDistributedLockMock(true);

var setupContext = new SetupContext { Errors = new Dictionary<string, string> { { "Error", "Test error" } } };
_mockAutoSetupService.Setup(s => s.SetupTenantAsync(It.IsAny<TenantSetupOptions>(), It.IsAny<ShellSettings>()))
.ReturnsAsync((setupContext, false));

var httpContext = new DefaultHttpContext();
httpContext.RequestServices = new ServiceCollection()
.AddSingleton(_mockAutoSetupService.Object)
.BuildServiceProvider();

var middleware = new AutoSetupMiddleware(
next: (innerHttpContext) => Task.CompletedTask,
_mockShellHost.Object,
_shellSettings,
_mockShellSettingsManager.Object,
_mockDistributedLock.Object,
_mockOptions.Object);

// Act
await middleware.InvokeAsync(httpContext);

// Assert
Assert.Equal(StatusCodes.Status503ServiceUnavailable, httpContext.Response.StatusCode);
}

[Fact]
public async Task InvokeAsync_UnInitializedShell_PerformsSetup()
{
// Arrange
_shellSettings.State = TenantState.Uninitialized;

SetupDistributedLockMock(true);

var setupContext = new SetupContext();
_mockAutoSetupService.Setup(s => s.SetupTenantAsync(It.IsAny<TenantSetupOptions>(), It.IsAny<ShellSettings>()))
.ReturnsAsync((setupContext, true));

var httpContext = new DefaultHttpContext();
httpContext.RequestServices = new ServiceCollection()
.AddSingleton(_mockAutoSetupService.Object)
.BuildServiceProvider();

var middleware = new AutoSetupMiddleware(
next: (innerHttpContext) => Task.CompletedTask,
_mockShellHost.Object,
_shellSettings,
_mockShellSettingsManager.Object,
_mockDistributedLock.Object,
_mockOptions.Object);

// Act
await middleware.InvokeAsync(httpContext);

// Assert
Assert.Equal(StatusCodes.Status302Found, httpContext.Response.StatusCode); // Redirect
_mockAutoSetupService.Verify(s => s.SetupTenantAsync(It.IsAny<TenantSetupOptions>(), It.IsAny<ShellSettings>()), Times.Once);
}

[Fact]
public async Task InvokeAsync_FailedLockAcquisition_ThrowsTimeoutException()
{
// Arrange
_shellSettings.State = TenantState.Uninitialized;

SetupDistributedLockMock(false);

var httpContext = new DefaultHttpContext();

var middleware = new AutoSetupMiddleware(
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can create a private method for middleware creation to make reusable across the unit tests

next: (innerHttpContext) => Task.CompletedTask,
_mockShellHost.Object,
_shellSettings,
_mockShellSettingsManager.Object,
_mockDistributedLock.Object,
_mockOptions.Object);

// Act & Assert
await Assert.ThrowsAsync<TimeoutException>(() => middleware.InvokeAsync(httpContext));
}

private void SetupDistributedLockMock(bool acquireLock)
{
var mockLocker = new Mock<ILocker>();
_mockDistributedLock
.Setup(d => d.TryAcquireLockAsync(It.IsAny<string>(), It.IsAny<TimeSpan>(), It.IsAny<TimeSpan>()))
.ReturnsAsync((mockLocker.Object, acquireLock));
}
}