Files
slp-modular-cms/src/SlpModularCms.Api.AndreaSlopFotografie.Tests/ContactHostTests.cs
T

265 lines
11 KiB
C#

using System.Net;
using System.Net.Http.Json;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using FluentAssertions;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using SlpModularCms.Modules.Contact.Data;
using SlpModularCms.Modules.Contact.Data.Entities;
namespace SlpModularCms.Api.AndreaSlopFotografie.Tests;
/// <summary>
/// The real Andrea Slop Fotografie host with the Contact module, against a real MariaDB/MySQL (like the other
/// host tests: set <c>ConnectionStrings__DefaultConnection</c> to a server you may create databases on; every
/// factory uses its own throw-away database).
/// </summary>
public class AsfContactHostFactory : WebApplicationFactory<Program>
{
private readonly Dictionary<string, string?> _settings;
private readonly string _databaseName = "AsfContactHost_" + Guid.NewGuid().ToString("N")[..12];
/// <summary>When set, the pipeline sees this as the TCP peer (the reverse proxy) of every request.</summary>
public string? PeerAddress { get; init; }
public AsfContactHostFactory(Dictionary<string, string?>? settings = null) => _settings = settings ?? [];
private static string BaseConnectionString =>
Environment.GetEnvironmentVariable("ConnectionStrings__DefaultConnection")
?? throw new InvalidOperationException("Set ConnectionStrings__DefaultConnection to a MariaDB/MySQL server for the host tests.");
private string ConnectionString =>
Regex.IsMatch(BaseConnectionString, "Database=[^;]*", RegexOptions.IgnoreCase)
? Regex.Replace(BaseConnectionString, "Database=[^;]*", $"Database={_databaseName}", RegexOptions.IgnoreCase)
: $"{BaseConnectionString};Database={_databaseName}";
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.UseEnvironment("Development");
builder.ConfigureAppConfiguration((_, config) =>
{
var all = new Dictionary<string, string?>
{
["ConnectionStrings:DefaultConnection"] = ConnectionString,
["Availability:StatusCacheSeconds"] = "0",
};
foreach (var (key, value) in _settings) all[key] = value;
config.AddInMemoryCollection(all);
});
if (PeerAddress is not null)
{
// Stands in for the reverse proxy: the TCP peer of every request. Runs before the forwarded-headers step.
builder.ConfigureServices(services => services.AddTransient<IStartupFilter>(_ => new PeerFilter(PeerAddress)));
}
}
private sealed class PeerFilter(string address) : IStartupFilter
{
public Action<IApplicationBuilder> Configure(Action<IApplicationBuilder> next) => app =>
{
app.Use((context, nextMiddleware) =>
{
context.Connection.RemoteIpAddress = IPAddress.Parse(address);
return nextMiddleware();
});
next(app);
};
}
public async Task<T> WithDb<T>(Func<ContactDbContext, Task<T>> action)
{
await using var scope = Services.CreateAsyncScope();
return await action(scope.ServiceProvider.GetRequiredService<ContactDbContext>());
}
public async Task OpenCmsSwitchAsync()
{
_ = CreateClient(); // starts the host (migrates the contact tables)
await WithDb(async db =>
{
db.ContactSettings.Add(new ContactSettings { Enabled = true, UpdatedAt = DateTimeOffset.UtcNow, UpdatedByUserId = Guid.NewGuid() });
await db.SaveChangesAsync();
return 0;
});
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
try
{
using var scope = Services.CreateScope();
scope.ServiceProvider.GetRequiredService<ContactDbContext>().Database.EnsureDeleted();
}
catch
{
// Best effort clean-up of the throw-away database.
}
}
base.Dispose(disposing);
}
}
/// <summary>The committed defaults, nothing overridden.</summary>
public sealed class AsfDefaultContactHostFactory() : AsfContactHostFactory(null);
internal static class ContactHttp
{
public const string Route = "/api/v1/contact-messages";
public static async Task<string> GetTokenAsync(HttpClient client, string? forwardedFor = null)
{
var request = new HttpRequestMessage(HttpMethod.Get, $"{Route}/token");
if (forwardedFor is not null) request.Headers.Add("X-Forwarded-For", forwardedFor);
var response = await client.SendAsync(request);
response.StatusCode.Should().Be(HttpStatusCode.OK);
using var json = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
return json.RootElement.GetProperty("token").GetString()!;
}
public static Task<HttpResponseMessage> PostAsync(HttpClient client, string token, string name, string? forwardedFor = null)
{
var request = new HttpRequestMessage(HttpMethod.Post, Route)
{
Content = new StringContent(JsonSerializer.Serialize(new
{
name, email = "jan@example.nl", subject = "Portretfotografie", message = "Hallo", hpCheck = "", token,
}), Encoding.UTF8, "application/json"),
};
request.Headers.Add("Idempotency-Key", Guid.NewGuid().ToString());
if (forwardedFor is not null) request.Headers.Add("X-Forwarded-For", forwardedFor);
return client.SendAsync(request);
}
}
public class AsfContactDisabledByDefaultTests : IClassFixture<AsfDefaultContactHostFactory>
{
private readonly AsfDefaultContactHostFactory _factory;
public AsfContactDisabledByDefaultTests(AsfDefaultContactHostFactory factory) => _factory = factory;
[Fact]
public async Task TheCommittedDefaults_KeepTheContactModuleLoadedButClosed()
{
var client = _factory.CreateClient();
using var caps = JsonDocument.Parse(await client.GetStringAsync("/api/v1/System/capabilities"));
caps.RootElement.GetProperty("modules").EnumerateArray().Select(e => e.GetString()).Should().Contain("Contact");
var token = await client.GetAsync($"{ContactHttp.Route}/token");
token.StatusCode.Should().Be(HttpStatusCode.NotFound);
(await token.Content.ReadAsStringAsync()).Should().BeEmpty();
(await client.PostAsync(ContactHttp.Route, null)).StatusCode.Should().Be(HttpStatusCode.NotFound);
}
}
public class AsfContactGateTests : IClassFixture<AsfOpenContactHostFactory>
{
private readonly AsfOpenContactHostFactory _factory;
public AsfContactGateTests(AsfOpenContactHostFactory factory) => _factory = factory;
[Fact]
public async Task ThePublicContactRoutes_StayReachable_WhileTheCmsIsNotAvailable_ButTheManagementRoutesAreGated()
{
await _factory.OpenCmsSwitchAsync();
// Switch the CMS off through the availability state of the real database (status 1 = not available).
await _factory.WithDb(db => db.Database.ExecuteSqlRawAsync(
"INSERT INTO AvailabilityState (Id, Status, Message, LastUpdatedAt, UpdatedBy) VALUES (UUID(), 1, 'host test', NOW(), 'host test')"));
var client = _factory.CreateClient();
(await client.GetAsync($"{ContactHttp.Route}?pageSize=1")).StatusCode
.Should().Be(HttpStatusCode.ServiceUnavailable, "the gate really is closed for everything not marked public");
var token = await ContactHttp.GetTokenAsync(client);
var post = await ContactHttp.PostAsync(client, token, "ASF Gate");
post.StatusCode.Should().Be(HttpStatusCode.Accepted);
(await _factory.WithDb(db => db.ContactMessages.CountAsync(m => m.Name == "ASF Gate"))).Should().Be(1);
(await _factory.WithDb(db => db.ContactMessages.SingleAsync(m => m.Name == "ASF Gate"))).SiteId.Should().Be("andreaslop");
}
}
public sealed class AsfOpenContactHostFactory() : AsfContactHostFactory(new()
{
["Contact:Enabled"] = "true",
["Contact:MinSeconds"] = "0",
["RateLimiting:ContactForm:PermitLimit"] = "1000",
["RateLimiting:ContactToken:PermitLimit"] = "1000",
});
/// <summary>One form submission allowed per window: the buckets show who shares one.</summary>
public sealed class AsfBehindProxyWithKnownProxyFactory() : AsfContactHostFactory(new()
{
["Contact:Enabled"] = "true",
["Contact:MinSeconds"] = "0",
["RateLimiting:ContactForm:PermitLimit"] = "1",
["RateLimiting:ContactToken:PermitLimit"] = "1000",
});
public sealed class AsfBehindProxyWithoutKnownProxyFactory() : AsfContactHostFactory(new()
{
["Contact:Enabled"] = "true",
["Contact:MinSeconds"] = "0",
["RateLimiting:ContactForm:PermitLimit"] = "1",
["RateLimiting:ContactToken:PermitLimit"] = "1000",
});
public class AsfRateLimitBehindIisTests
{
[Fact]
public async Task WithTheProxyKnown_EachVisitorAddressHasItsOwnBucket()
{
// The proxy list is read while the host is being composed, before test configuration is applied, so (like in
// production) it comes from the environment: ForwardedHeaders__KnownProxies__0.
Environment.SetEnvironmentVariable("ForwardedHeaders__KnownProxies__0", "10.1.1.1");
try
{
await RunWithKnownProxyAsync();
}
finally
{
Environment.SetEnvironmentVariable("ForwardedHeaders__KnownProxies__0", null);
}
}
private static async Task RunWithKnownProxyAsync()
{
using var factory = new AsfBehindProxyWithKnownProxyFactory { PeerAddress = "10.1.1.1" };
await factory.OpenCmsSwitchAsync();
var client = factory.CreateClient();
var a1 = await ContactHttp.PostAsync(client, await ContactHttp.GetTokenAsync(client, "203.0.113.10"), "ASF A1", "203.0.113.10");
var a2 = await ContactHttp.PostAsync(client, await ContactHttp.GetTokenAsync(client, "203.0.113.10"), "ASF A2", "203.0.113.10");
var b1 = await ContactHttp.PostAsync(client, await ContactHttp.GetTokenAsync(client, "203.0.113.20"), "ASF B1", "203.0.113.20");
a1.StatusCode.Should().Be(HttpStatusCode.Accepted);
a2.StatusCode.Should().Be(HttpStatusCode.TooManyRequests, "the same visitor is limited");
b1.StatusCode.Should().Be(HttpStatusCode.Accepted, "another visitor has a bucket of their own");
}
[Fact]
public async Task WithoutKnownProxies_TheWholeSiteSharesOneBucket_WhichIsWhyItIsAReleaseCondition()
{
using var factory = new AsfBehindProxyWithoutKnownProxyFactory { PeerAddress = "10.1.1.1" };
await factory.OpenCmsSwitchAsync();
var client = factory.CreateClient();
var a = await ContactHttp.PostAsync(client, await ContactHttp.GetTokenAsync(client, "203.0.113.10"), "ASF Shared A", "203.0.113.10");
var b = await ContactHttp.PostAsync(client, await ContactHttp.GetTokenAsync(client, "203.0.113.20"), "ASF Shared B", "203.0.113.20");
a.StatusCode.Should().Be(HttpStatusCode.Accepted);
b.StatusCode.Should().Be(HttpStatusCode.TooManyRequests, "forwarded addresses are ignored without KnownProxies: everybody is the proxy");
}
}