Mail: diagnose van SMTP-weigeringen en keuze bij een nieuwe uitnodigingslink
SMTP: bij een geweigerd commando logt de verzender fase, statuscode en de eerste regel van het serverantwoord (adressen vervangen, max 120 tekens); specifiekere foutcodes (rejected_sender, rejected_recipient, tls_failed, connection_failed) die de beheerder in het venster ziet; opstartlog met SMTP-host, poort en standaard afzenderdomein. Uit de property-test: besturingstekens worden eerst verwijderd, anders kon een adres weer aan elkaar plakken. Nieuwe uitnodigingslink: regenerate-invite mailt alleen met sendEmail=true (standaard false); eerst een keuzevenster 'Alleen link kopieren' / 'Link kopieren en mailen' (zonder mail alleen de link). Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -19,10 +19,17 @@ internal sealed class StubSmtpServer : IDisposable
|
||||
public List<string> Recipients { get; } = [];
|
||||
public int Port => ((IPEndPoint)_listener.LocalEndpoint).Port;
|
||||
|
||||
private readonly string? _rejectMailFrom;
|
||||
private readonly string? _rejectRcpt;
|
||||
|
||||
/// <param name="silent">Accept connections but never answer (to provoke the timeout).</param>
|
||||
public StubSmtpServer(bool silent = false)
|
||||
/// <param name="rejectMailFrom">Reply to MAIL FROM with this full line (for example "553 5.7.1 ...").</param>
|
||||
/// <param name="rejectRcpt">Reply to RCPT TO with this full line.</param>
|
||||
public StubSmtpServer(bool silent = false, string? rejectMailFrom = null, string? rejectRcpt = null)
|
||||
{
|
||||
_silent = silent;
|
||||
_rejectMailFrom = rejectMailFrom;
|
||||
_rejectRcpt = rejectRcpt;
|
||||
_listener.Start();
|
||||
_loop = Task.Run(Serve);
|
||||
}
|
||||
@@ -41,8 +48,8 @@ internal sealed class StubSmtpServer : IDisposable
|
||||
while (await reader.ReadLineAsync() is { } line)
|
||||
{
|
||||
if (line.StartsWith("EHLO", StringComparison.OrdinalIgnoreCase)) await writer.WriteLineAsync("250 stub");
|
||||
else if (line.StartsWith("MAIL FROM", StringComparison.OrdinalIgnoreCase)) { MailFrom = line; await writer.WriteLineAsync("250 ok"); }
|
||||
else if (line.StartsWith("RCPT TO", StringComparison.OrdinalIgnoreCase)) { Recipients.Add(line); await writer.WriteLineAsync("250 ok"); }
|
||||
else if (line.StartsWith("MAIL FROM", StringComparison.OrdinalIgnoreCase)) { MailFrom = line; await writer.WriteLineAsync(_rejectMailFrom ?? "250 ok"); }
|
||||
else if (line.StartsWith("RCPT TO", StringComparison.OrdinalIgnoreCase)) { Recipients.Add(line); await writer.WriteLineAsync(_rejectRcpt ?? "250 ok"); }
|
||||
else if (line.StartsWith("DATA", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
await writer.WriteLineAsync("354 go");
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
using System.Net.Sockets;
|
||||
using FluentAssertions;
|
||||
using FsCheck;
|
||||
using FsCheck.Fluent;
|
||||
using MailKit.Net.Smtp;
|
||||
using MailKit.Security;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using SlpModularCms.Core.Email;
|
||||
using Xunit.Abstractions;
|
||||
|
||||
namespace SlpModularCms.Core.Tests.Email;
|
||||
|
||||
public class SmtpFailureTests(ITestOutputHelper output)
|
||||
{
|
||||
[Theory]
|
||||
[InlineData("553 5.7.1 <no-reply@slpsoftware.nl>: Sender address rejected", "[adres]")]
|
||||
[InlineData("550 relay denied for jan@example.org", "relay denied for [adres]")]
|
||||
[InlineData("554 user@host.example.nl: not allowed", "[adres]: not allowed")]
|
||||
public void SafeReply_ReplacesEveryAddress(string reply, string expectedFragment)
|
||||
{
|
||||
var safe = SmtpFailure.SafeReply(reply);
|
||||
|
||||
safe.Should().Contain(expectedFragment);
|
||||
safe.Should().NotContain("@");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SafeReply_ControlCharactersCannotGlueAnAddressTogether()
|
||||
{
|
||||
// Found by the property test: "x-@" CR "host.example.nl" becomes an address once the CR is removed.
|
||||
var safe = SmtpFailure.SafeReply("550 x-@\rhost.example.nl y");
|
||||
|
||||
safe.Should().NotContain("@");
|
||||
safe.Should().Contain("[adres]");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SafeReply_KeepsOnlyTheFirstLine_DropsControlCharacters_AndCutsLongText()
|
||||
{
|
||||
SmtpFailure.SafeReply("550 first line\r\n550-second line with secret").Should().Be("550 first line");
|
||||
SmtpFailure.SafeReply("550 bad\u0000char\u0007").Should().Be("550 badchar");
|
||||
var cut = SmtpFailure.SafeReply("550 " + new string('x', 400));
|
||||
cut.Length.Should().BeLessThanOrEqualTo(SmtpFailure.MaxReplyLength + 3);
|
||||
cut.Should().EndWith("...");
|
||||
SmtpFailure.SafeReply(null).Should().BeEmpty();
|
||||
SmtpFailure.SafeReply(" ").Should().BeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Classify_IsAsSpecificAsTheFailureAllows()
|
||||
{
|
||||
var none = CancellationToken.None;
|
||||
SmtpFailure.Classify(new SmtpCommandException(SmtpErrorCode.SenderNotAccepted, SmtpStatusCode.MailboxUnavailable, "x"), none)
|
||||
.Should().Be(MailSendResult.RejectedSender);
|
||||
SmtpFailure.Classify(new SmtpCommandException(SmtpErrorCode.RecipientNotAccepted, SmtpStatusCode.MailboxUnavailable, "x"), none)
|
||||
.Should().Be(MailSendResult.RejectedRecipient);
|
||||
SmtpFailure.Classify(new SmtpCommandException(SmtpErrorCode.MessageNotAccepted, SmtpStatusCode.TransactionFailed, "x"), none)
|
||||
.Should().Be(MailSendResult.Rejected);
|
||||
SmtpFailure.Classify(new AuthenticationException("bad pw-secret"), none).Should().Be(MailSendResult.AuthFailed);
|
||||
SmtpFailure.Classify(new TimeoutException(), none).Should().Be(MailSendResult.Timeout);
|
||||
SmtpFailure.Classify(new OperationCanceledException(), none).Should().Be(MailSendResult.Timeout);
|
||||
SmtpFailure.Classify(new SocketException(), none).Should().Be(MailSendResult.ConnectionFailed);
|
||||
SmtpFailure.Classify(new InvalidOperationException(), none).Should().Be(MailSendResult.Unknown);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Describe_ForACommandNamesPhaseAndStatus_ForAuthNeverTheReply()
|
||||
{
|
||||
var command = new SmtpCommandException(SmtpErrorCode.SenderNotAccepted, SmtpStatusCode.MailboxNameNotAllowed, "553 no for jan@example.org");
|
||||
var describedCommand = SmtpFailure.Describe(command);
|
||||
describedCommand.Should().Contain("SenderNotAccepted").And.Contain("MailboxNameNotAllowed(553)").And.Contain("[adres]");
|
||||
describedCommand.Should().NotContain("jan@example.org");
|
||||
|
||||
var auth = SmtpFailure.Describe(new AuthenticationException("535 wrong password pw-secret-123"));
|
||||
auth.Should().Contain("AuthenticationException").And.Contain("AUTH");
|
||||
auth.Should().NotContain("pw-secret-123").And.NotContain("535");
|
||||
}
|
||||
|
||||
// PBT-03: whatever a server says, the reply that reaches the log has no address, no control character and a bounded length.
|
||||
[Fact]
|
||||
public void Property_TheLoggedReply_NeverHasAnAddressOrControlCharacters_AndIsBounded()
|
||||
{
|
||||
string[] pieces = ["550 ", " ", "a", "Z9", "@", ".", "-", "_", "<", ">", "\r", "\n", "\0", "\t", "\"", "example", "nl", "user", "x", "😀", "é"];
|
||||
var arb = Gen.Elements(pieces).ArrayOf().Select(p => string.Concat(p)).ToArbitrary();
|
||||
Prop.ForAll(arb, reply =>
|
||||
{
|
||||
var safe = SmtpFailure.SafeReply(reply);
|
||||
return !safe.Any(char.IsControl)
|
||||
&& safe.Length <= SmtpFailure.MaxReplyLength + 3
|
||||
&& !System.Text.RegularExpressions.Regex.IsMatch(safe, @"[A-Za-z0-9._-]+@[A-Za-z0-9.-]+");
|
||||
}).Check(Config.QuickThrowOnFailure.WithMaxTest(1500));
|
||||
output.WriteLine("Property held for 1500 generated server replies.");
|
||||
}
|
||||
}
|
||||
|
||||
public class SmtpSenderDiagnosticsTests
|
||||
{
|
||||
private static (SmtpEmailSender Sender, LogCapture Logs) Sender(StubSmtpServer server)
|
||||
{
|
||||
var logs = new LogCapture();
|
||||
var factory = LoggerFactory.Create(b => b.AddProvider(logs));
|
||||
var sender = new SmtpEmailSender(
|
||||
Options.Create(new EmailOptions
|
||||
{
|
||||
FromAddress = "no-reply@slpsoftware.nl", FromName = "Site",
|
||||
Smtp = { Host = "127.0.0.1", Port = server.Port, EnableSsl = false, Username = "", Password = "", TimeoutSeconds = 5 }
|
||||
}),
|
||||
factory.CreateLogger<SmtpEmailSender>());
|
||||
return (sender, logs);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ARefusedSender_IsNamedAsSuch_AndTheLogShowsPhaseStatusAndARedactedReply_NoAddresses()
|
||||
{
|
||||
using var server = new StubSmtpServer(rejectMailFrom: "553 5.7.1 <no-reply@slpsoftware.nl>: Sender address rejected: not owned by user jan@andreaslop.nl");
|
||||
var (sender, logs) = Sender(server);
|
||||
|
||||
var result = await sender.SendAsync(new OutgoingMail("someone@gmail.com", "Subject", "<p>x</p>"));
|
||||
|
||||
result.Should().Be(MailSendResult.Fail(MailSendResult.RejectedSender));
|
||||
var line = logs.Entries.Should().ContainSingle(e => e.Level == LogLevel.Warning).Subject.Message;
|
||||
line.Should().Contain("rejected_sender").And.Contain("SenderNotAccepted").And.Contain("(553)")
|
||||
.And.Contain("[adres]").And.Contain("from_domain=slpsoftware.nl").And.Contain($"smtp_port={server.Port}");
|
||||
// No address of the sender, the recipient or the account, and not the server reply beyond the redacted first line.
|
||||
line.Should().NotContain("no-reply@").And.NotContain("someone@").And.NotContain("jan@").And.NotContain("gmail.com");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ARefusedRecipient_IsNamedAsSuch()
|
||||
{
|
||||
using var server = new StubSmtpServer(rejectRcpt: "550 5.7.1 <someone@gmail.com>: Relay access denied");
|
||||
var (sender, logs) = Sender(server);
|
||||
|
||||
var result = await sender.SendAsync(new OutgoingMail("someone@gmail.com", "Subject", "<p>x</p>"));
|
||||
|
||||
result.Should().Be(MailSendResult.Fail(MailSendResult.RejectedRecipient));
|
||||
logs.Entries.Single(e => e.Level == LogLevel.Warning).Message.Should().Contain("RecipientNotAccepted").And.NotContain("someone@");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TheLog_NeverContainsTheCredentials()
|
||||
{
|
||||
using var server = new StubSmtpServer(rejectMailFrom: "553 5.7.1 rejected");
|
||||
var logs = new LogCapture();
|
||||
var factory = LoggerFactory.Create(b => b.AddProvider(logs));
|
||||
var sender = new SmtpEmailSender(
|
||||
Options.Create(new EmailOptions
|
||||
{
|
||||
FromAddress = "no-reply@slpsoftware.nl", FromName = "Site",
|
||||
Smtp = { Host = "127.0.0.1", Port = server.Port, EnableSsl = false, Username = "user-secret-1", Password = "pw-secret-2", TimeoutSeconds = 5 }
|
||||
}),
|
||||
factory.CreateLogger<SmtpEmailSender>());
|
||||
|
||||
await sender.SendAsync(new OutgoingMail("someone@gmail.com", "Subject", "<p>x</p>"));
|
||||
|
||||
string.Join("\n", logs.Entries.Select(e => e.Message)).Should().NotContain("user-secret-1").And.NotContain("pw-secret-2");
|
||||
}
|
||||
}
|
||||
@@ -50,11 +50,24 @@ public sealed class MailAvailability : IMailAvailability
|
||||
}
|
||||
|
||||
/// <summary>Makes the decision (and its Error log line) happen at start-up instead of at the first mail.</summary>
|
||||
public sealed class MailStartupCheck(IMailAvailability availability, ILogger<MailStartupCheck> logger) : IHostedService
|
||||
public sealed class MailStartupCheck(IMailAvailability availability, IOptions<EmailOptions> email, ILogger<MailStartupCheck> logger) : IHostedService
|
||||
{
|
||||
public Task StartAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
logger.LogInformation("mail_status enabled={Enabled}", availability.IsEnabled);
|
||||
var o = email.Value;
|
||||
if (availability.IsEnabled)
|
||||
{
|
||||
// Where mail goes through and with which default sender DOMAIN (not the address): what a refused
|
||||
// MAIL FROM is checked against. A sender chosen in the site settings can differ from this default.
|
||||
var at = o.FromAddress.LastIndexOf('@');
|
||||
logger.LogInformation(
|
||||
"mail_status enabled=true smtp_host={Host} smtp_port={Port} starttls={StartTls} default_from_domain={FromDomain}",
|
||||
o.Smtp.Host, o.Smtp.Port, o.Smtp.EnableSsl, at >= 0 ? o.FromAddress[(at + 1)..] : "?");
|
||||
}
|
||||
else
|
||||
{
|
||||
logger.LogInformation("mail_status enabled=false");
|
||||
}
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
|
||||
@@ -8,6 +8,12 @@ public readonly record struct MailSendResult(bool Sent, string? ErrorCode)
|
||||
public const string Timeout = "timeout";
|
||||
public const string AuthFailed = "auth_failed";
|
||||
public const string Rejected = "rejected";
|
||||
/// <summary>The server refused the sender address (MAIL FROM): the From address is not allowed for this account.</summary>
|
||||
public const string RejectedSender = "rejected_sender";
|
||||
/// <summary>The server refused the recipient (RCPT TO), for instance because it does not relay for that domain.</summary>
|
||||
public const string RejectedRecipient = "rejected_recipient";
|
||||
public const string TlsFailed = "tls_failed";
|
||||
public const string ConnectionFailed = "connection_failed";
|
||||
public const string Unknown = "unknown";
|
||||
|
||||
public static MailSendResult Ok { get; } = new(true, null);
|
||||
|
||||
@@ -62,21 +62,15 @@ public sealed class SmtpEmailSender(IOptions<EmailOptions> options, ILogger<Smtp
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var code = Map(ex, cancellationToken);
|
||||
// The exception TYPE only: its message may contain the recipient or server replies.
|
||||
logger.LogWarning("identity_mail_failed code={Code} exception={ExceptionType}", code, ex.GetType().Name);
|
||||
var code = SmtpFailure.Classify(ex, cancellationToken);
|
||||
// Never the whole exception text (it can quote addresses or credentials): the type, for a refused
|
||||
// command its phase and status code, and a redacted, shortened first line of the server's reply.
|
||||
logger.LogWarning("identity_mail_failed code={Code} detail={Detail} from_domain={FromDomain} smtp_port={Port}",
|
||||
code, SmtpFailure.Describe(ex), DomainOf(fromAddress), _options.Smtp.Port);
|
||||
return MailSendResult.Fail(code);
|
||||
}
|
||||
}
|
||||
|
||||
private static string Map(Exception ex, CancellationToken callerToken) => ex switch
|
||||
{
|
||||
OperationCanceledException when !callerToken.IsCancellationRequested => MailSendResult.Timeout,
|
||||
TimeoutException => MailSendResult.Timeout,
|
||||
OperationCanceledException => MailSendResult.Unknown,
|
||||
AuthenticationException => MailSendResult.AuthFailed,
|
||||
SmtpCommandException or SmtpProtocolException or SslHandshakeException => MailSendResult.Rejected,
|
||||
ServiceNotConnectedException or ServiceNotAuthenticatedException => MailSendResult.Rejected,
|
||||
_ => MailSendResult.Unknown
|
||||
};
|
||||
private static string DomainOf(string address) =>
|
||||
address.Contains('@') ? address[(address.LastIndexOf('@') + 1)..] : "?";
|
||||
}
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
using System.Net.Sockets;
|
||||
using System.Text.RegularExpressions;
|
||||
using MailKit;
|
||||
using MailKit.Net.Smtp;
|
||||
using MailKit.Security;
|
||||
|
||||
namespace SlpModularCms.Core.Email;
|
||||
|
||||
/// <summary>
|
||||
/// What went wrong with a mail, in two forms: a short code for the screen (<see cref="Classify"/>) and a
|
||||
/// careful one-line description for the log (<see cref="Describe"/>).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The exception text is still not logged as a whole (it can quote the recipient, the sender and credentials). The
|
||||
/// description is explicit and limited: status code and phase, then at most the first line of the server's reply,
|
||||
/// with every e-mail address replaced by [adres] and cut to <see cref="MaxReplyLength"/> characters. Credentials
|
||||
/// never appear in a server reply to MAIL/RCPT, and the AUTH reply text is not included at all.
|
||||
/// </remarks>
|
||||
public static partial class SmtpFailure
|
||||
{
|
||||
public const int MaxReplyLength = 120;
|
||||
|
||||
[GeneratedRegex(@"[^\s@<>""'(),;:]+@[^\s@<>""'(),;:]+")]
|
||||
private static partial Regex AddressPattern();
|
||||
|
||||
/// <summary>The short code shown to the administrator; the most specific one the failure allows.</summary>
|
||||
public static string Classify(Exception ex, CancellationToken callerToken) => ex switch
|
||||
{
|
||||
OperationCanceledException when !callerToken.IsCancellationRequested => MailSendResult.Timeout,
|
||||
TimeoutException => MailSendResult.Timeout,
|
||||
OperationCanceledException => MailSendResult.Unknown,
|
||||
AuthenticationException => MailSendResult.AuthFailed,
|
||||
SslHandshakeException => MailSendResult.TlsFailed,
|
||||
SmtpCommandException c => c.ErrorCode switch
|
||||
{
|
||||
SmtpErrorCode.SenderNotAccepted => MailSendResult.RejectedSender,
|
||||
SmtpErrorCode.RecipientNotAccepted => MailSendResult.RejectedRecipient,
|
||||
_ => MailSendResult.Rejected
|
||||
},
|
||||
SmtpProtocolException => MailSendResult.Rejected,
|
||||
ServiceNotConnectedException or ServiceNotAuthenticatedException => MailSendResult.Rejected,
|
||||
SocketException => MailSendResult.ConnectionFailed,
|
||||
_ => MailSendResult.Unknown
|
||||
};
|
||||
|
||||
/// <summary>The log description of a failure: the type, and for a refused command its phase, status code and a redacted first line.</summary>
|
||||
public static string Describe(Exception ex)
|
||||
{
|
||||
var type = ex.GetType().Name;
|
||||
if (ex is SmtpCommandException c)
|
||||
{
|
||||
var status = (int)c.StatusCode;
|
||||
return $"{type} phase={c.ErrorCode} smtp_status={c.StatusCode}({status}) reply=\"{SafeReply(c.Message)}\"";
|
||||
}
|
||||
if (ex is AuthenticationException) return $"{type} phase=AUTH"; // the reply text is deliberately left out
|
||||
return type;
|
||||
}
|
||||
|
||||
/// <summary>The first line of a server reply: addresses replaced, control characters dropped, cut short.</summary>
|
||||
public static string SafeReply(string? reply)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(reply)) return "";
|
||||
var firstLine = reply.Split('\n', 2)[0].Trim();
|
||||
// Control characters go FIRST: removed afterwards they could glue the parts of an address together again.
|
||||
var printable = new string(firstLine.Where(ch => !char.IsControl(ch)).ToArray());
|
||||
var cleaned = AddressPattern().Replace(printable, "[adres]").Replace('"', '\'');
|
||||
return cleaned.Length <= MaxReplyLength ? cleaned : cleaned[..MaxReplyLength] + "...";
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,8 @@ namespace SlpModularCms.Core.Identity.Models;
|
||||
[ExcludeFromCodeCoverage] public record CompleteSetupRequest(string Token, string Password, string? Name = null);
|
||||
[ExcludeFromCodeCoverage] public record ChangeRoleRequest(string NewRole);
|
||||
[ExcludeFromCodeCoverage] public record ForgotPasswordRequest(string Email);
|
||||
/// <summary>SendEmail is false unless the caller says so: a new link is never mailed by surprise.</summary>
|
||||
[ExcludeFromCodeCoverage] public record RegenerateInviteRequest(bool SendEmail = false);
|
||||
[ExcludeFromCodeCoverage] public record ResetPasswordRequest(Guid UserId, string Token, string NewPassword);
|
||||
[ExcludeFromCodeCoverage] public record UpdateProfileRequest(string Name, string Email, string? Language = null);
|
||||
[ExcludeFromCodeCoverage] public record ChangePasswordRequest(string CurrentPassword, string NewPassword);
|
||||
|
||||
@@ -174,6 +174,30 @@ public class UsersApiWithRealTokensTests : IAsyncLifetime
|
||||
(await RoleOfAsync(user.Id)).Should().Be("User");
|
||||
}
|
||||
|
||||
// ---- regenerate-invite: the body is optional and the mail is only sent on request
|
||||
|
||||
[Fact]
|
||||
public async Task RegenerateInvite_OverHttp_MailsOnlyWhenAskedTo_WhateverTheBodyLooksLike()
|
||||
{
|
||||
await AddUserAsync("andrea@test.nl", "Owner");
|
||||
var id = Guid.NewGuid();
|
||||
_invitations.GetAllPendingInvitationsAsync().Returns(new List<PendingInvitationInfo>
|
||||
{
|
||||
new(id, "invited@test.com", "User", "old", DateTimeOffset.UtcNow.AddDays(-2), true, "nl")
|
||||
});
|
||||
_invitations.RegenerateInvitationAsync(id).Returns("fresh");
|
||||
_mail.SendInvitationAsync(default!, default!, default, default, default).ReturnsForAnyArgs(MailSendResult.Ok);
|
||||
var token = await TokenAsync("andrea@test.nl");
|
||||
|
||||
(await SendAsync(token, HttpMethod.Post, $"/Users/{id}/regenerate-invite")).Should().Be(HttpStatusCode.OK); // no body at all
|
||||
(await SendAsync(token, HttpMethod.Post, $"/Users/{id}/regenerate-invite", new { })).Should().Be(HttpStatusCode.OK); // {}
|
||||
(await SendAsync(token, HttpMethod.Post, $"/Users/{id}/regenerate-invite", new { sendEmail = false })).Should().Be(HttpStatusCode.OK);
|
||||
await _mail.DidNotReceiveWithAnyArgs().SendInvitationAsync(default!, default!, default, default, default);
|
||||
|
||||
(await SendAsync(token, HttpMethod.Post, $"/Users/{id}/regenerate-invite", new { sendEmail = true })).Should().Be(HttpStatusCode.OK);
|
||||
await _mail.Received(1).SendInvitationAsync("invited@test.com", "fresh", "nl", true, Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
// ---- the Administrator is held to the hierarchy
|
||||
|
||||
[Fact]
|
||||
|
||||
@@ -154,19 +154,81 @@ public class UsersControllerMailTests : IDisposable
|
||||
// --- regenerate / resend ---
|
||||
|
||||
[Fact]
|
||||
public async Task Regenerate_SendsTheNewLinkMail_InTheLanguageOfTheInvitation()
|
||||
public async Task Regenerate_WithTheFlag_SendsTheNewLinkMail_InTheLanguageOfTheInvitation()
|
||||
{
|
||||
var owner = await Add("owner@test.com", "Owner");
|
||||
var id = Guid.NewGuid();
|
||||
Pending(id, language: "en");
|
||||
_invitations.RegenerateInvitationAsync(id).Returns("new-token");
|
||||
|
||||
var result = await As(owner).RegenerateInvite(id);
|
||||
var result = await As(owner).RegenerateInvite(id, new RegenerateInviteRequest(SendEmail: true));
|
||||
|
||||
Prop<string>(result.Should().BeOfType<OkObjectResult>().Subject.Value, "inviteLink").Should().Contain("new-token");
|
||||
var body = result.Should().BeOfType<OkObjectResult>().Subject.Value;
|
||||
Prop<string>(body, "inviteLink").Should().Contain("new-token");
|
||||
Prop<bool>(Prop<object>(body, "mail"), "sent").Should().BeTrue();
|
||||
await _mail.Received(1).SendInvitationAsync("invited@test.com", "new-token", "en", true, Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Regenerate_WithoutTheFlag_CreatesTheLink_ButSendsNoMail()
|
||||
{
|
||||
var owner = await Add("owner@test.com", "Owner");
|
||||
var id = Guid.NewGuid();
|
||||
Pending(id);
|
||||
_invitations.RegenerateInvitationAsync(id).Returns("new-token");
|
||||
|
||||
var result = await As(owner).RegenerateInvite(id, new RegenerateInviteRequest());
|
||||
|
||||
var body = result.Should().BeOfType<OkObjectResult>().Subject.Value;
|
||||
Prop<string>(body, "inviteLink").Should().Contain("new-token");
|
||||
Prop<object?>(body, "mail").Should().BeNull();
|
||||
await _invitations.Received(1).RegenerateInvitationAsync(id);
|
||||
await _mail.DidNotReceiveWithAnyArgs().SendInvitationAsync(default!, default!, default, default, default);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Regenerate_WithNoBodyAtAll_IsTheSameAsWithoutTheFlag()
|
||||
{
|
||||
var owner = await Add("owner@test.com", "Owner");
|
||||
var id = Guid.NewGuid();
|
||||
Pending(id);
|
||||
_invitations.RegenerateInvitationAsync(id).Returns("new-token");
|
||||
|
||||
var result = await As(owner).RegenerateInvite(id); // an older client sends no flag
|
||||
|
||||
Prop<object?>(result.Should().BeOfType<OkObjectResult>().Subject.Value, "mail").Should().BeNull();
|
||||
await _mail.DidNotReceiveWithAnyArgs().SendInvitationAsync(default!, default!, default, default, default);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Regenerate_WithTheFlag_OnASiteWithoutMail_HasNoMailResult()
|
||||
{
|
||||
var owner = await Add("owner@test.com", "Owner");
|
||||
var id = Guid.NewGuid();
|
||||
Pending(id);
|
||||
_invitations.RegenerateInvitationAsync(id).Returns("new-token");
|
||||
_mail.SendInvitationAsync(default!, default!, default, default, default).ReturnsForAnyArgs(MailSendResult.Fail(MailSendResult.Disabled));
|
||||
|
||||
var result = await As(owner).RegenerateInvite(id, new RegenerateInviteRequest(true));
|
||||
|
||||
Prop<object?>(result.Should().BeOfType<OkObjectResult>().Subject.Value, "mail").Should().BeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Regenerate_WithTheFlag_ReportsAFailedMail_NextToTheLink()
|
||||
{
|
||||
var owner = await Add("owner@test.com", "Owner");
|
||||
var id = Guid.NewGuid();
|
||||
Pending(id);
|
||||
_invitations.RegenerateInvitationAsync(id).Returns("new-token");
|
||||
_mail.SendInvitationAsync(default!, default!, default, default, default).ReturnsForAnyArgs(MailSendResult.Fail(MailSendResult.RejectedSender));
|
||||
|
||||
var body = (await As(owner).RegenerateInvite(id, new RegenerateInviteRequest(true))).Should().BeOfType<OkObjectResult>().Subject.Value;
|
||||
|
||||
Prop<string>(Prop<object>(body, "mail"), "error").Should().Be("rejected_sender");
|
||||
Prop<string>(body, "inviteLink").Should().Contain("new-token");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Resend_OfAValidInvitation_SendsTheExistingLink_WithoutCreatingANewOne()
|
||||
{
|
||||
|
||||
@@ -166,10 +166,11 @@ public class UsersController : ControllerBase
|
||||
|
||||
/// <summary>
|
||||
/// Issues a fresh link for an open (or expired) invitation: new token and a new lifetime. The
|
||||
/// old link stops working. Until e-mail exists this is how an administrator re-sends one.
|
||||
/// old link stops working. It is mailed only when the request says <c>sendEmail: true</c> (the administrator
|
||||
/// is asked); otherwise the link is just returned so it can be copied and shared.
|
||||
/// </summary>
|
||||
[HttpPost("{invitationId:guid}/regenerate-invite")]
|
||||
public async Task<IActionResult> RegenerateInvite(Guid invitationId)
|
||||
public async Task<IActionResult> RegenerateInvite(Guid invitationId, [FromBody] RegenerateInviteRequest? request = null)
|
||||
{
|
||||
var invitation = await GetInvitationAsync(invitationId);
|
||||
if (invitation is null) return NotFound();
|
||||
@@ -180,8 +181,12 @@ public class UsersController : ControllerBase
|
||||
var token = await _invitationService.RegenerateInvitationAsync(invitationId);
|
||||
if (token is null) return NotFound();
|
||||
|
||||
var link = $"/invite/complete?token={Uri.EscapeDataString(token)}";
|
||||
if (request?.SendEmail != true)
|
||||
return Ok(new { inviteLink = link, mail = (object?)null });
|
||||
|
||||
var mail = await _mail.SendInvitationAsync(invitation.Email, token, invitation.Language, isNewLink: true, HttpContext.RequestAborted);
|
||||
return Ok(new { inviteLink = $"/invite/complete?token={Uri.EscapeDataString(token)}", mail = MailBody(mail) });
|
||||
return Ok(new { inviteLink = link, mail = MailBody(mail) });
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
Reference in New Issue
Block a user