Verify mailer credentials against ProcessWeb API before showing E-Mail-Dienst as healthy
Playwright Tests / test (push) Canceled after 0s

The Admin status pill previously turned green whenever the mailer was
enabled in config, without proving the account/token actually work.
Add IComService.VerifyCredentialsAsync (GET /mailer/fc?fn=verify, also
passing serverid when configured so the API confirms this server
belongs to the account) and wire it into a new "email" system-status
probe, so the pill only goes green once the Mailer API itself confirms
the credentials.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
Stefan
2026-09-15 23:51:32 +02:00
co-authored by Claude Sonnet 5
parent f36f65789e
commit 107b7f54f1
10 changed files with 339 additions and 28 deletions
+17 -8
View File
@@ -1,6 +1,6 @@
---
status: Active
lastUpdated: 2026-09-09
lastUpdated: 2026-09-15
applyTo:
- "Fuchs/Controllers/IntranetController.Admin.cs"
- "Fuchs/Services/SystemStatusService.cs"
@@ -56,15 +56,24 @@ click "Administration" → $ocms.init('admin')
**never the password**), email (mailer enabled/base-url/account/server-id/token-present +
OverrideRecipient), blob (enabled/configured/containers), MFR (host/creds-present/sync),
Key Vault (vault-uri/app-prefix/managed-secret-count/client-registered).
- Probes (`database`, `keyvault`, `blob`, `mfr`) each return a `SystemProbeResult`
- Probes (`database`, `email`, `keyvault`, `blob`, `mfr`) each return a `SystemProbeResult`
(`status` = `ok`/`error`/`disabled`/`unconfigured`, `ok`, `message`, `detail`, `durationMs`,
optional `metrics`). They never throw — failures are captured in the result. `database` runs
`SELECT @@SERVERNAME, DB_NAME(), SUSER_SNAME()`; `keyvault` reads the first managed secret via
the DI `SecretClient`; `blob` calls `IBlobStorageService.CheckConnectivityAsync` (account-info
request **plus a per-container blob count** for the invoice/reminder containers, surfaced as
`metrics` and totalled in the message); `mfr` calls `IMfrClientFactory.Create().GetEntities()`.
The generic `metrics` (label/value pairs) is how a probe reports extra facts for display — the
blob probe uses it for the file counts.
`SELECT @@SERVERNAME, DB_NAME(), SUSER_SNAME()`; `email` calls
`IComService.VerifyCredentialsAsync` (GET `{BaseUrl}/mailer/fc?fn=verify` with the configured
Basic-auth account/token — see the Mailer API contract) and only turns `ok` when the Mailer API
itself confirms the credentials (`ok:true`); when `ProcessWebComSettings.ServerId` is configured
it is sent along as `&serverid=...` so the API also confirms this server belongs to the account
(an account/token that is valid but for a server the account doesn't own comes back `ok:false`
with the mismatched `serverid` echoed, surfaced in `detail`); a configured-but-wrong token
surfaces as `error`, never as a false-positive `ok` — the `mailerEnabled`/`tokenConfigured` flags
in `GetInfo()` describe configuration only and were never proof the credentials actually work;
`keyvault` reads
the first managed secret via the DI `SecretClient`; `blob` calls
`IBlobStorageService.CheckConnectivityAsync` (account-info request **plus a per-container blob
count** for the invoice/reminder containers, surfaced as `metrics` and totalled in the message);
`mfr` calls `IMfrClientFactory.Create().GetEntities()`. The generic `metrics` (label/value pairs)
is how a probe reports extra facts for display — the blob probe uses it for the file counts.
- `SendTestEmailAsync(to, subject, body)` HTML-encodes the body and sends via `IComService`, so
the `Fuchs:Email:OverrideRecipient` redirect applies exactly as for any other mail; the result
reports the requested recipient and, when active, the override target.
+26
View File
@@ -27,4 +27,30 @@ public interface IComService
/// <param name="message">Text message body.</param>
/// <returns><c>true</c> when the SMS was accepted successfully.</returns>
Task<bool> SendSmsAsync(string mobile, string message);
/// <summary>
/// Verifies the configured account/token against the Mailer API's credential-check
/// endpoint (GET {BaseUrl}/mailer/fc?fn=verify) without sending anything.
/// </summary>
Task<MailerCredentialsCheckResult> VerifyCredentialsAsync(CancellationToken cancellationToken = default);
}
/// <summary>Outcome of a Mailer API credential verification (see <see cref="IComService.VerifyCredentialsAsync"/>).</summary>
public sealed class MailerCredentialsCheckResult
{
/// <summary><c>true</c> only when the Mailer API confirmed the credentials (HTTP 200, <c>ok:true</c>).</summary>
public bool Ok { get; init; }
/// <summary>Account name the Mailer API echoed back, when verified.</summary>
public string? Account { get; init; }
/// <summary>
/// Server ID the Mailer API echoed back. Only present when a <c>serverid</c> was sent with
/// the request (i.e. <see cref="ProcessWebComSettings.ServerId"/> is configured); in that
/// case <see cref="Ok"/> is only <c>true</c> when this server belongs to the account too.
/// </summary>
public string? ServerId { get; init; }
/// <summary>Human-readable failure detail (status code / body / exception message), never the token.</summary>
public string? Detail { get; init; }
}
+58
View File
@@ -199,6 +199,64 @@ public class ProcessWebComService : IComService
}
}
public async Task<MailerCredentialsCheckResult> VerifyCredentialsAsync(CancellationToken cancellationToken = default)
{
if (string.IsNullOrWhiteSpace(_settings.AccountId) || string.IsNullOrWhiteSpace(_settings.Token))
return new MailerCredentialsCheckResult { Ok = false, Detail = "Konto-ID oder Token nicht konfiguriert." };
var client = _httpClientFactory.CreateClient("ProcessWebMailer");
string credentials = Convert.ToBase64String(
Encoding.UTF8.GetBytes($"{_settings.AccountId}:{_settings.Token}"));
// Passing serverid makes the Mailer API also confirm that THIS server is one of the
// account's usable servers, not just that the account/token pair is valid.
string url = $"{_settings.BaseUrl}/mailer/fc?fn=verify";
if (!string.IsNullOrWhiteSpace(_settings.ServerId))
url += $"&serverid={Uri.EscapeDataString(_settings.ServerId)}";
using var request = new HttpRequestMessage(HttpMethod.Get, url);
request.Headers.Authorization = new AuthenticationHeaderValue("Basic", credentials);
try
{
using var response = await client.SendAsync(request, cancellationToken);
string body = await response.Content.ReadAsStringAsync(cancellationToken);
if (!response.IsSuccessStatusCode)
return new MailerCredentialsCheckResult
{
Ok = false,
Detail = $"API-Fehler {(int)response.StatusCode} ({response.StatusCode}): {body}",
};
var payload = JsonConvert.DeserializeObject<MailerVerifyResponse>(body);
bool ok = payload?.Ok == true;
string? detail = ok ? null
: (!string.IsNullOrWhiteSpace(payload?.ServerId)
? $"Server-ID '{payload!.ServerId}' gehört nicht zu diesem Mailer-Konto."
: "Mailer API meldete ungültige Zugangsdaten.");
return new MailerCredentialsCheckResult
{
Ok = ok,
Account = payload?.Account,
ServerId = payload?.ServerId,
Detail = detail,
};
}
catch (Exception ex)
{
_logger.LogWarning(ex, "VerifyCredentialsAsync failed");
return new MailerCredentialsCheckResult { Ok = false, Detail = ex.Message };
}
}
private sealed class MailerVerifyResponse
{
public bool Ok { get; set; }
public string? Account { get; set; }
public string? ServerId { get; set; }
}
// ── Private helpers ────────────────────────────────────────────────────────
private async Task<(bool ok, System.Net.HttpStatusCode status, string body)> PostToApiAsync(string reference, string comtype, object communication)
+1 -1
View File
@@ -6,7 +6,7 @@ namespace Fuchs.Services;
/// </summary>
public sealed class SystemProbeResult
{
/// <summary>Probe identifier: <c>database</c>, <c>keyvault</c>, <c>blob</c> or <c>mfr</c>.</summary>
/// <summary>Probe identifier: <c>database</c>, <c>email</c>, <c>keyvault</c>, <c>blob</c> or <c>mfr</c>.</summary>
public string Component { get; init; } = "";
/// <summary><c>ok</c> | <c>error</c> | <c>disabled</c> | <c>unconfigured</c>.</summary>
+28 -1
View File
@@ -20,7 +20,7 @@ namespace Fuchs.Services;
/// </summary>
public sealed class SystemStatusService : ISystemStatusService
{
private static readonly string[] Components = { "database", "keyvault", "blob", "mfr" };
private static readonly string[] Components = { "database", "email", "keyvault", "blob", "mfr" };
private readonly IConfiguration _configuration;
private readonly IHostEnvironment _environment;
@@ -177,6 +177,7 @@ public sealed class SystemStatusService : ISystemStatusService
result = component switch
{
"database" => await ProbeDatabaseAsync(cancellationToken),
"email" => await ProbeEmailAsync(cancellationToken),
"keyvault" => await ProbeKeyVaultAsync(cancellationToken),
"blob" => await ProbeBlobAsync(cancellationToken),
"mfr" => await ProbeMfrAsync(cancellationToken),
@@ -268,6 +269,32 @@ public sealed class SystemStatusService : ISystemStatusService
}
}
private async Task<SystemProbeResult> ProbeEmailAsync(CancellationToken ct)
{
if (!_mailer.Enabled)
return SystemProbeResult.Disabled("email", "Mailer ist deaktiviert (Fuchs:Mailer:Enabled=false).");
if (string.IsNullOrWhiteSpace(_mailer.AccountId) || string.IsNullOrWhiteSpace(_mailer.Token))
return SystemProbeResult.Unconfigured("email", "Konto-ID oder Token nicht konfiguriert.");
MailerCredentialsCheckResult check = await _comService.VerifyCredentialsAsync(ct);
bool checkedServerId = !string.IsNullOrWhiteSpace(_mailer.ServerId);
string okMessage = checkedServerId
? "Zugangsdaten und Server-ID beim Mailer verifiziert."
: "Zugangsdaten beim Mailer verifiziert.";
string? okDetail = checkedServerId && !string.IsNullOrWhiteSpace(check.ServerId)
? $"{check.Account} (Server: {check.ServerId})"
: check.Account;
return new SystemProbeResult
{
Component = "email",
Status = check.Ok ? "ok" : "error",
Ok = check.Ok,
Message = check.Ok ? okMessage : "Zugangsdaten konnten nicht verifiziert werden.",
Detail = check.Ok ? okDetail : check.Detail,
};
}
private async Task<SystemProbeResult> ProbeKeyVaultAsync(CancellationToken ct)
{
string appName = _configuration["SecretManagement:AppName"] ?? "";
+5 -8
View File
@@ -38,7 +38,7 @@ let $adm = {
$$.dc('adm_sec', frm).text($adt.sub_status);
let grid = $$.dc('adm_grid', frm);
$adm.dbCard(grid, info.database || {}, pmap.database);
$adm.mailCard(grid, info.email || {});
$adm.mailCard(grid, info.email || {}, pmap.email);
$adm.blobCard(grid, info.blob || {}, pmap.blob);
$adm.mfrCard(grid, info.mfr || {}, pmap.mfr);
$adm.kvCard(grid, info.keyVault || {}, pmap.keyvault);
@@ -176,12 +176,7 @@ let $adm = {
[$adt.login, d.userId]
], probe);
},
mailCard: function (grid, e) {
let card = $$.dc('adm_card', grid);
let hd = $$.dc('adm_card_hd', card);
$$.s($adt.mail).appendTo(hd);
$adm.setPill($$.sc('adm_pill').appendTo(hd), { status: e.mailerEnabled === true ? 'ok' : 'disabled' });
let bd = $$.dc('adm_card_bd', card);
mailCard: function (grid, e, probe) {
let rows = [
[$adt.mailer, $adm.yesNo(e.mailerEnabled === true)],
[$adt.baseurl, e.baseUrl],
@@ -191,7 +186,9 @@ let $adm = {
[$adt.overrideActive, $adm.yesNo(e.overrideActive === true)]
];
if (e.overrideActive === true) { rows.push([$adt.override, e.overrideRecipient]); }
$adm.kvTable(bd, rows);
// The pill only turns green once the credentials are verified against the Mailer API
// (probe 'email', GET /mailer/fc?fn=verify) — mailerEnabled alone is not proof they work.
let card = $adm.probeCard(grid, $adt.mail, 'email', rows, probe);
let ft = $$.dc('adm_card_ft', card);
$$.bbtn($adt.testmail_btn, 'adm_btn adm_btn_primary').appendTo(ft).click($adm.testMailDlg);
},
+5 -8
View File
@@ -123,7 +123,7 @@ let $adm = {
$$.dc('adm_sec', frm).text($adt.sub_status);
let grid = $$.dc('adm_grid', frm);
$adm.dbCard(grid, info.database || {}, pmap.database);
$adm.mailCard(grid, info.email || {});
$adm.mailCard(grid, info.email || {}, pmap.email);
$adm.blobCard(grid, info.blob || {}, pmap.blob);
$adm.mfrCard(grid, info.mfr || {}, pmap.mfr);
$adm.kvCard(grid, info.keyVault || {}, pmap.keyvault);
@@ -261,12 +261,7 @@ let $adm = {
[$adt.login, d.userId]
], probe);
},
mailCard: function (grid, e) {
let card = $$.dc('adm_card', grid);
let hd = $$.dc('adm_card_hd', card);
$$.s($adt.mail).appendTo(hd);
$adm.setPill($$.sc('adm_pill').appendTo(hd), { status: e.mailerEnabled === true ? 'ok' : 'disabled' });
let bd = $$.dc('adm_card_bd', card);
mailCard: function (grid, e, probe) {
let rows = [
[$adt.mailer, $adm.yesNo(e.mailerEnabled === true)],
[$adt.baseurl, e.baseUrl],
@@ -276,7 +271,9 @@ let $adm = {
[$adt.overrideActive, $adm.yesNo(e.overrideActive === true)]
];
if (e.overrideActive === true) { rows.push([$adt.override, e.overrideRecipient]); }
$adm.kvTable(bd, rows);
// The pill only turns green once the credentials are verified against the Mailer API
// (probe 'email', GET /mailer/fc?fn=verify) — mailerEnabled alone is not proof they work.
let card = $adm.probeCard(grid, $adt.mail, 'email', rows, probe);
let ft = $$.dc('adm_card_ft', card);
$$.bbtn($adt.testmail_btn, 'adm_btn adm_btn_primary').appendTo(ft).click($adm.testMailDlg);
},
File diff suppressed because one or more lines are too long